在实际指针的副本上使用 free() 是可以接受的/正确的吗?

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

这是:

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

与此相同:

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

如果是,无需解释,如果不是,请说明原因!

是的,它们是等价的。

引用 C11,章节 §7.22.3.3,(强调我的

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.

因此,只要您传递之前由 malloc() 或家人返回的相同 ptr 值(指针本身或其副本),您就可以开始了。

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

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

#define myfunc(x) do_something(&x)

那么 myfunc(x) 几乎肯定会得到与 myfunc(y) 不同的结果,即使 x == y,因为 true 函数是 do_something(),以及传递给它的参数 &x&y。即使 x 等于 y&x 不等于 &y,所以传递给函数的参数实际上在值上并不相等,函数的行为是因此预计会有所不同。