Carlos Pinto
Carlos Pinto

Reputation: 45

Using free() on a copy of the actual pointer is acceptable / correct?

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!

Upvotes: 2

Views: 1299

Answers (2)

mwag
mwag

Reputation: 4045

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.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134346

Yes, they are equivalent.

Quoting C11, chapter §7.22.3.3, (emphasis mine)

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr 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 to free or realloc, 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.

Upvotes: 2

Related Questions