我正试图让段错误,但我无法得到它,我想知道为什么。
#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;
}
好的,据我了解它只能正常工作,因为该字符串未从内存中释放。 即我们很幸运。 在这里,我们有未定义的行为。我是对的吗?
提前谢谢!!
答案 0 :(得分:4)
由于您的程序没有无效的内存引用,因此您不会遇到分段错误。我猜你认为""I should be freed"
是在堆栈上创建的,然后以某种方式被破坏或释放,这是一个错误的假设,因为它是一个常量字符串文字,它被放入程序数据段并且是&# 34;活&#34;为你的计划的生命。
即使它是动态分配并在离开作用域时自动释放,在这种情况下,您仍然不能指望您的程序接收SIGSEGV
。因为未定义的行为并不总是导致分段错误。
另外,尽量不要写char *data = "blah-blah";
。假定字符串文字始终是常量,并且尝试修改它们是未定义的行为。虽然人们仍然围绕着这个sometimes。
答案 1 :(得分:2)
char *line = "I should be freed";
您仍然可以看到内容,因为字符串文字具有静态存储持续时间。这里字符串文字I should be freed
驻留在只读位置,并在程序执行完成后释放。
该程序没有未定义的行为。