Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 669
space_voyager Avatar asked Oct 19 '16 14:10

space_voyager


1 Answers

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.

like image 181
Bathsheba Avatar answered Oct 13 '22 18:10

Bathsheba