search

Home  >  Q&A  >  body text

c++ - 把一个指向数组的指针delete[]之后,赋值成为指向另一个更长的数组,然后delete[] 这个指针,是否会造成内存泄漏

int _tmain(int argc, _TCHAR* argv[])
{
    int* p = new int[3]{1, 2, 3};
    int* k = new int[4]{6, 7, 8, 9};

    delete[] p;
    p = k;
    delete[] p;//此处是否会造成内存泄漏?

    return 0;
}

意思就是说,p初始化时指向的是一个长度为3的数组,而p后来指向了k,那么此时再delete[] p的话,是释放3个单位空间还是4个单位空间?假如只释放3个单位,那就内存泄漏了。
或者换一种说法: delete[] 总要知道需要释放的长度吧。这个长度信息,是跟指针p绑在一起的还是和指针指向的这片地址空间绑在一起的?
如果我是语言设计者的话,我会选择后者,不知我想的对不对。

ringa_leeringa_lee2814 days ago641

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:26:22

    No, new and delete deal with the memory on the heap. The management method of the heap usually adds some information about this memory in front of the applied memory, such as the length, so you must specify one when you create new. The length is not needed when deleting. You only need to specify whether it is a single or an array.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:26:22

    No, the specific length and other information, as well as its relationship with the pointer, are all completed by the compiler and operating system, and programmers do not need to care about the underlying implementation.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:26:22

    Will not cause memory leaks.
    p initializes to point to an array of length 3, and then points to an array of length 4. Because you have performed a delete operation before, there will be no memory leak. The pointer p declared here is stored on the stack, and the new one is stored in the heap. What is stored in p is the address of the array you declared. The address in p is the address of the array you applied for on the heap. You need to use delete to release it. Failure to release it will cause memory leaks.
    Delete does not need to know the specific length of the array. It only needs to select delete or delete[] depending on whether it is an array.

    reply
    0
  • Cancelreply