space_voyager space_voyager - 1 month ago 16
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
and
delete c
are equivalent, and that both will free the memory space holding
a
, thus
a
is no longer accessible?

Answer

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.

Comments