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

冷暖自知 提交于 2020-01-17 08:20:29

问题


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




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!