我试图得到段错误,但我无法得到它,我想知道为什么。
#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;
}
好的,据我了解,它只能正常工作,因为该字符串没有从内存中释放。即我们只是幸运。在这里,我们有未定义的行为。我对吗?
先感谢您!!