Mir*_*zov 2 c++ memory-management dynamic-allocation
在以下代码中:
int main(int argc,char * argv[]){
int * ptr;
ptr = 0; // tried also with NULL , nothing changes
ptr = new int[10]; // allocating 10 integers
ptr[2] = 5;
ptr[15] = 15; // this should cause error (seg fault) - but it doesn't
cout << ptr[2] << endl;
cout << ptr[15] << endl; // no error here
delete [] ptr;
cout << ptr[2] << endl; // prints the value 5
cout << ptr[15] << endl; // prints the value 15
}
Run Code Online (Sandbox Code Playgroud)
执行结果是:
Run Code Online (Sandbox Code Playgroud)5 15 5 15
我尝试使用这样的单一分配删除:
int * ptr;
ptr = 0;
ptr = new int;
*ptr = 5;
cout << *ptr << endl;
delete ptr ;
cout << *ptr << endl;
Run Code Online (Sandbox Code Playgroud)
结果是正常的:
Run Code Online (Sandbox Code Playgroud)5 0
在fedora 17和另一个平台(SLC5 - 基于red hat的linux)上使用gcc 4.7.2和gcc 4.1.2进行测试,以确保它不依赖于编译器.我在这做错了什么?
超出预期的数组大小的元素存在,因为那里的内存恰好存在.对它采取任何行动都是非法的,并导致黑暗未知.
释放意味着不再为您分配内存.这并不意味着有人去那里清理它.但访问你剩下的东西是非法的,并导致黑暗的未知.