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 ?
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])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With