c++ - 这段代码会做什么? (内存管理)

标签 c++ memory-management

char *p = new char[200];
char *p1 = p;
char *p2 = &p[100];
delete [] p1;

顺便说一句,这不是测试,也不是我真正需要知道的任何东西 :)

最佳答案

 // allocate memory for 200 chars
 // p points to the begining of that 
 // block
 char *p = new char[200];
 // we don't know if allocation succeeded or not
 // no null-check or exception handling

 // **Update:** Mark. Or you use std::no_throw or set_new_handler. 
 // what happens next is not guranteed

 // p1 now points to the same location as p
 char *p1 = p;

 // another pointer to char which points to the
 // 100th character of the array, note that
 // this can be treated as a pointer to an array
 // for the remaining 100-odd elements
 char *p2 = &p[100];

 // free the memory for 200 chars
 delete [] p1;

 // **Update:** Doug. T
 // [...] p and p2 are now pointing to freed memory 
 // and accessing it will be undefined behavior 
 // depending on the executing environment.

关于c++ - 这段代码会做什么? (内存管理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/763213/

相关文章:

c++ - Visual C++ 2008 发布版本打破了我的花车

c++ - 使用 GLUT_DOUBLE 模式绘制形状

c++ - HoughLinesP 和 opencv 内存管理

c++ - 重复使用可变参数函数参数不起作用

c++ - 如何获取页面的 "full source"?

c++ - 连词模板不会短路

c++ - _heapwalk报告_HEAPBADNODE,导致断点或无限循环

c - Stack 和 Heap 中的内存分配

java - 实习一个字符串

c++ - 是否可以在编译时加载/读取 shape_predictor_68_face_landmarks.dat?