【问题标题】:What would this code do? (memory management)这段代码会做什么? (内存管理)
【发布时间】:2009-04-18 09:38:12
【问题描述】:
char *p = new char[200];
char *p1 = p;
char *p2 = &p[100];
delete [] p1;

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

【问题讨论】:

    标签: c++ memory-management


    【解决方案1】:
     // 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.
    

    【讨论】:

    • 您可以重新分配 - 正常的方法是分配一个 100 字节大小的新块,然后将第二个 100 字节复制到该块中
    • 不,您不能进行分区删除。您必须拨打第二个新电话,复制您要保存的部分并删除原件。
    • @dirkgently:您的第二条评论不正确 - 如果分配失败,则会引发异常,这意味着只有在分配成功时才会执行第二行。您不需要检查 null
    • 在编译前禁用异常。因为我不知道我提到的编译器选项。我看不出这次讨论的价值。
    • 或者你使用 std::no_throw 或 set_new_handler。禁用异常是不正常的,因此失败通常会终止程序。所以它可能失败,因为它没有被指定,最好澄清一下。此外,p 和 p2 不能在最后一行之后使用(并不总是很明显)。
    猜你喜欢
    • 2011-10-27
    • 2023-03-19
    • 1970-01-01
    • 2016-05-31
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多