gpt4 book ai didi

C++试图使构造函数失败

转载 作者:行者123 更新时间:2023-11-30 00:53:25 25 4
gpt4 key购买 nike

我正在尝试获取段错误,但我无法获取它,我想知道为什么。

#include <iostream>
using namespace std;


class A{

public:
char *field_;

A(char *field):field_(field) {
// I believe(suppose) that it's equal to
// field_ = field;
// so actual initial string wasn't copied, only a pointer to it
}
void show() {
cout<<field_<<"\n";
}
};

int main(){

A *obj;

{
char *line="I should be freed";
obj = new (nothrow) A(line);
}

// After exiting from the previous scope,
// char *line variable should be freed.
// Constructor of class A didn't make byte for byte
//copying, so we cannot have
// access to it for sure

for(int i=0;i<4;i++) // trying to clear stack and erase char *line variable
char something[10000];

obj->show(); // and it works correctly!!!! why?


delete obj;
return 0;
}

好的,据我所知,它之所以能正常工作,只是因为该字符串没有从内存中释放出来。IE。我们只是幸运。在这里我们有未定义的行为。我说得对吗?

提前致谢!!

最佳答案

您不会遇到段错误,因为您的程序没有无效的内存引用。我猜你认为 ""I should be freed" 是在堆栈上创建的,然后以某种方式被销毁或释放,这是一个错误的假设,因为它是一个常量字符串文字,它被放入程序数据段,并且在程序的生命周期内是“有效的”。

即使它是动态分配的并且在离开作用域时自动释放,您仍然不能期望您的程序在那种情况下接收到 SIGSEGV。因为未定义的行为并不总是导致段错误。

此外,尽量不要写 char *data = "blah-blah";。假定字符串文字始终是常量,尝试修改它们是未定义的行为。尽管人们仍然围绕这个 sometimes 进行破解.

关于C++试图使构造函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16490930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com