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?
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?
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 delete
d pointer is undefined behavior - your program might crash or misbehave otherwise.
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.
Definetly, no. The delete
operation doesn't change the pointer itself - it frees the memory addressed by that pointer.
delete x
is allowed to change the value of x
: #5002555 –
Agostino 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.
© 2022 - 2024 — McMap. All rights reserved.
0
to a deleted pointer is a controversial subject, depending on the situation, as it might hide structural bugs in the flow / memory handling. Better use smart pointers / containers and not have to calldelete
at all. – Sling