问题
Is this:
int *a = malloc (sizeof (int) );
int *b = a;
free (b);
the same as this:
int *a = malloc (sizeof (int) );
free (a);
If yes, no need to explain, but if no, please elaborate why not!
回答1:
Yes, they are equivalent.
Quoting C11
, chapter §7.22.3.3, (emphasis mine)
The
free
function causes the space pointed to byptr
to be deallocated, that is, made available for further allocation. Ifptr
is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call tofree
orrealloc
, the behavior is undefined.
So, as long as you pass the same ptr
value (the pointer itself or a copy of it) which was earlier returned by malloc()
or family, you're good to go.
回答2:
The reason that free(x)
is the same as free(y)
when x == y
has nothing to do with the free()
function. This is simply due to the fact that free()
is a function. In C, any function's arguments are passed by value. So for any function f
, f(x)
is equivalent to f(y)
so long as y == x
.
As an aside, this is not necessarily true for function-like macros, that may look like functions, but are not in fact. So if you have a macro such as:
#define myfunc(x) do_something(&x)
then myfunc(x)
will almost certainly have a different result from myfunc(y)
even if x == y
, because the true function is do_something()
, and the arguments being passed to it &x
and &y
. Even if x
equals y
, &x
does not equal &y
, so the arguments being passed to the function are not in fact equal in value and the behavior of the function is therefore expected to be different.
来源:https://stackoverflow.com/questions/43456215/using-free-on-a-copy-of-the-actual-pointer-is-acceptable-correct