在实际指针的副本上使用free()是可接受的/正确的吗? [英] Using free() on a copy of the actual pointer is acceptable / correct?

查看:106
本文介绍了在实际指针的副本上使用free()是可接受的/正确的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是

int *a = malloc (sizeof (int) );
int *b = a;
free (b);

与此相同:

int *a = malloc (sizeof (int) );
free (a);

如果是,则无需解释,但如果否,请详细说明原因!

解决方案

x == yfree()函数无关时,free(x)free(y)相同的原因.这完全是因为free()是一个函数.在C语言中,任何函数的参数都按值传递.因此,对于任何功能f,只要y == xf(x)就等同于f(y).

顺便说一句,对于函数似的宏,它不一定是正确的,它可能看起来像函数,但实际上不是.因此,如果您有一个宏,例如:

#define myfunc(x) do_something(&x)

然后,即使x == ymyfunc(x)几乎肯定会与myfunc(y)产生不同的结果,因为 true 函数是do_something(),并且将参数传递给它&x&y.即使x等于y&x也不等于&y,所以传递给该函数的参数的值实际上并不相等,因此该函数的行为将有所不同.

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!

解决方案

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.

这篇关于在实际指针的副本上使用free()是可接受的/正确的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆