Any reasons why this can not be standard behavior of free()
?
multiple pointers pointing to the same object:
#include
#i
Bjarne Stroustrup discussing whether the delete operator should zero its operand. It's not the free() function, but it's a good discussion anyway. Consider points like:
He also says it was intended but never happened with operator delete
:
C++ explicitly allows an implementation of delete to zero out an lvalue operand, and I had hoped that implementations would do that, but that idea doesn't seem to have become popular with implementers.
Casting the reference from int *&
to void *&
is not guaranteed to work. int *
simply does not have to have the same size, representation nor alignment requirements as void *
.
The proper C++ solution would be to use templates, as Neil Butterworth suggests in a comment. And neither of these ways work in C, obviously - which is where free()
comes from.
What's this maniac thing with zero ? There are other numbers !
Why should a free pointer should contain zero more than any other distinguished value ?
Practically, in my C++ code I often use watchdog objects and when freeing a pointer reset it not to zero but to the watchdog. That has the added benefit that the methods of the object can still be called with the existing interface and is much more secure and efficient that resetting pointer to zero (it avoid testing objects for zero, I just call the object).
If a free like function say zfree(void * & p) would set p to zero it would forbid my watchdog style (or at least would'nt help).
And as others pointer out , what would be the point to reset a pointer to zero if it goes out of scope ? Just useless code. And what if there is other pointers that contain the same adress, etc.
Because function parameters are passed by value in C. That is, if p == 0x12345 you pass '0x12345' to free(), not p "itself".
In C, calling a function can never alter the value of the parameters you pass in, so if free(p)
altered the value of p
by setting it to NULL
then this behaviour would be very non-standard indeed.
Simple answer: because you might be freeing an expression, e.g. free(find_named_object("foo"))
.
In more detail: The free
function takes a void*
parameter, which is the address of the memory to free. This doesn't confer to the function any knowledge of the original variable that supplied the address (or, for that matter, whether there even exists a variable). Just setting the parameter passed in to NULL would do nothing either, since it's just a local copy of the address.