space_voyager space_voyager - 1 year ago 104
C++ Question

C++ delete a pointer (free memory)

Consider the following code:

int a = 10;
int * b = &a;
int * c = b;
delete b; // equivalent to delete c;

Am I correct to understand in the last line,
delete b
delete c
are equivalent, and that both will free the memory space holding
, thus
is no longer accessible?

Answer Source

The behaviour of your program is undefined. You can only use delete on a pointer to memory that you have allocated using new. If you had written

int* b = new int;
*b = 10;
int* c = b;

then you could write either delete b; or delete c; to free your memory. Don't attempt to derefererence either b or c after the delete call though, the behaviour on doing that is also undefined.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download