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

Mic*_*ael 2 c++ memory-management

char *p = new char[200];
char *p1 = p;
char *p2 = &p[100];
delete [] p1;
Run Code Online (Sandbox Code Playgroud)

顺便说一下,这不是测试或任何我真正需要知道的事情:)

dir*_*tly 13

 // 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.
Run Code Online (Sandbox Code Playgroud)

  • @dirkgently:你的第二个评论不正确 - 如果分配失败,将抛出异常,这意味着第二行仅在分配成功时执行.您不需要检查null (3认同)
  • 您可以重新分配 - 常规方法是分配一个大小为100字节的新块,然后将第二个100字节复制到该块中 (2认同)
  • 不,你不能分区删除.您必须进行第二次新呼叫,复制要保存的部分并删除原始部分. (2认同)
  • 您在编译之前禁用了异常.因为我不知道我提到的编译器选项.我没有看到这次讨论的优点. (2认同)