我试图得到段故障,但我不能得到它,我想知道为什么。
#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;
}
好的,据我所知,它正确工作只是因为字符串没有从内存中释放。也就是说,我们只是幸运而已。这里我们有未定义的行为。我说的对吗?
提前感谢!!
你不会得到一个分段错误,因为没有无效的内存引用由你的程序。我猜你认为""I should be freed"
是在堆栈上创建的,然后以某种方式被销毁或释放,这是一个错误的假设,因为它是一个常量字符串字面值,它被放置在程序数据段中,并且在程序的生命周期内是"活的"。
即使它是动态分配并在离开作用域时自动释放的,在这种情况下,您仍然不能期望您的程序接收到SIGSEGV
。因为未定义的行为并不总是导致分段错误。
另外,尽量不要写char *data = "blah-blah";
。假定字符串字面值始终是常量,尝试修改它们是未定义的行为。尽管有时人们还是会破解这个问题
char *line = "I should be freed";
您仍然可以看到内容,因为字符串字面值具有静态存储持续时间。在这里,字符串字面值I should be freed
驻留在只读位置,一旦程序执行完成,它将被释放。
程序没有未定义行为