Search code examples
cpointersmallocfree

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!


Solution

  • 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.