Reputation: 29
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 ?
Upvotes: 2
Views: 146
Reputation: 338
No, it won't. In C++, it's comma operator . Quote from wiki:
In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).
Therefore, in that statement
delete ptr, ptr = 0;
is equivalent to
delete ptr; // executed first, its return value is ignored
ptr = 0; // the return value of '=', which is '0' is returned by ',' operator
Upvotes: 3
Reputation: 8636
Delete ptr will free up dynamically allocated memory, whereas ptr=0 makes sure that pointer is now a "null" pointer so you dont get any weird/unexpected behavior
Upvotes: 0
Reputation: 502
The statement delete ptr
will make the pointer become the overhang pointer
. This stands for you can't use the pointer anymore, but now actually it still point to a valid memory address. So you need to use ptr=0
for making it be a nullptr
. This is always a safe way to use the ptr
. I hope this can help you.
Upvotes: 0
Reputation: 29266
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])
Upvotes: 4
Reputation: 20794
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.
Upvotes: 3
Reputation: 198324
Frees the memory, then nulls the pointer so no-one could get confused that the pointer is still pointing at a valid location. Note that x, y
is evaluated the same as x; y
, the only difference being that the former doesn't work with statements (and is an expression, itself).
Upvotes: 1