简体   繁体   English

删除前删除指针是否会导致内存泄漏?

[英]Does Nulling a pointer before delete gives memory leak?

int *p = new int;

p = NULL;

delete p;

is this a memory leak ??? 这是一个内存泄漏??? because the memory location pointed to by pointer p is not freed, its just the pointer that has been NULLed and when we delete, it does not vacate that memory location. 因为指针p指向的内存位置没有被释放,它只是已经为NULL的指针,当我们删除它时,它不会腾出那个内存位置。 Is that so ? 是这样吗 ?

Yes, it does. 是的,它确实。 Yes, it is so. 是的,就是这样。 Need more characters! 需要更多角色!

The reason you will get a memory leak is because p will no longer point to the object that you want to delete. 您将获得内存泄漏的原因是因为p将不再指向您要删除的对象。

You typically want to make p NULL after you delete, mostly as a safeguard to double delete, but it is not required. 您通常希望在删除后使用p NULL,这主要是为了保护双重删除,但这不是必需的。 There is no ill effect in delete'ing a NULL pointer, though. 但是,删除NULL指针没有任何不良影响。

A pointer is just a value pointing to some address of memory - the pointer is not(!) allocated memory! 指针只是指向某个内存地址的值 - 指针不是(!)分配的内存! Hence having a new will ask some allocator to reserve some amount of memory and return the address. 因此,有一个新的将要求一些分配器保留一些内存并返回地址。 A delete will ask the same allocator to free that memory. 删除将要求相同的分配器释放该内存。 Setting the pointer to zero (before deletion) defeats it and leads to a memory leak. 将指针设置为零(删除之前)会使其失败并导致内存泄漏。

First of all, deleting a NULL pointer in C++ is actually 'no work done'. 首先,在C ++中删除NULL指针实际上是“没有工作”。 It does not give any error too, which sometimes may give you an illusion that the NULL pointer got successfully deleted. 它也没有给出任何错误,这有时可能会让你觉得NULL指针被成功删除了。

Secondly, since the address to which the pointer p was pointing, let say 1000 (memory address value), had no one else other than this very pointer to identify it, and now that you have changed this only recognizer of 1000 and set it to NULL, the thing which happened is that this 1000 has acquired a memory space but now could not be deleted as "how the hell could I delete something if I don't even know where it is". 其次,既然指针p所指向的地址,就说1000(内存地址值),除了这个非常指针识别它之外没有其他人,现在你已经改变了这个只有1000的识别器并将其设置为NULL,发生的事情是这1000已经获得了一个内存空间,但现在无法删除为“如果我甚至不知道它在哪里,我该怎么删除它”。 Hence it is a memory leak. 因此它是一个内存泄漏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM