What happens to an address after delete operator has been applied to it in C++?

半腔热情 提交于 2019-12-29 07:45:11

问题


If I delete a pointer as follows for example:

delete myPointer;

And, after that did not assign 0 to the pointer as follows:

myPointer = 0; //skipped this

Will myPointer be pointing to another memory address?


回答1:


No, in most implementations it will store the same address as previously - delete usually doesn't change the address and unless you assign a new address value it remains unchanged. However this is not always guaranteed.

Don't forget, that doing anything except assigning a null pointer or another valid pointer to an already deleted pointer is undefined behavior - your program might crash or misbehave otherwise.




回答2:


myPointer would be pointing to the same memory address. But, it wouldn't be valid for you to use the memory at that address because delete would have given it back to the runtime/operating system, and the operating system my have allocated that memory for use by something else.




回答3:


Definetly, no. The delete operation doesn't change the pointer itself - it frees the memory addressed by that pointer.




回答4:


This question is important! I have seen that Visual Studio 2017 has changed pointer value after "delete". It coused a problem because I has using memory tracing tool. The tool was collecting pointers after each operator "new" and was checking them after "delete". Pseudo code:

Data* New(const size_t count)
{
    Data* const ptr(new Data[count]);
    #ifdef TEST_MODE
    MemoryDebug.CollectPointer(ptr);
    #endif
    return ptr;
}

void Delete(Data* const ptr)
{
    delete[] ptr;
    #ifdef TEST_MODE
    MemoryDebug.CheckPointer(ptr);
    #endif
}

This code works good on Visual Studio 2008 but was failing on Visual Studio 2017 so I have changed the order of operations in second function.

However the question is good and the problem exists. Experienced engineers should be aware of that.



来源:https://stackoverflow.com/questions/4990462/what-happens-to-an-address-after-delete-operator-has-been-applied-to-it-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!