Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ What does delete pointer,pointer=0; statement work ? Does it clear memory twice?

Tags:

c++

int *ptr = new int(10);    
printf("%d \n",*ptr);    
delete ptr,ptr=0;    
printf("%d",ptr);   

Output:
10
0

My question here is how this statment "delete ptr,ptr = 0" works ? Does it free the memory twice ?

like image 618
Tony Issac Avatar asked Feb 23 '26 05:02

Tony Issac


2 Answers

The pointer and the memory the pointer points to are 2 different things. Setting the pointer to 0 after you delete it is just an added safety mechanism to ensure you don't try to use a memory address that you shouldn't.

int *ptr = new int(10);

ptr will have a value like 0xabcd1234, but *ptr will be 10 You can "do stuff" with the memory address 0xabcd1234 because it's allocated to you.

printf("%d \n",*ptr);
delete ptr,ptr=0;

delete ptr "gives back" the memory, but you still have it's address (that's dangerous_. ptr = 0 means you forget the address, so all is good.

I guess the "trick" is the comma operator: delete ptr,ptr=0; which as other have said means "do the left hand part, then the right hand part." If you try to get a result (int i_know_it_is_a_stupid_example = 10,20; the result is the RHS [20])

like image 160
John3136 Avatar answered Feb 25 '26 17:02

John3136


delete ptr

Frees the memory at the address pointed to by ptr. However, ptr still points to that memory address.

ptr = 0

ptr no longer points to a specific memory address.

Therefore, the point of ptr = 0 is to enable the programmer to test whether the pointer is still usable (in use). If you don't set ptr = 0, but only delete ptr, ptr will still point to a location in memory which may contain garbage information.

like image 25
Inisheer Avatar answered Feb 25 '26 17:02

Inisheer