这是:
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 byptr
to be deallocated, that is, made available for further allocation. Ifptr
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 tofree
orrealloc
, the behavior is undefined.
因此,只要您传递先前由 malloc()
或系列返回的相同 ptr
值(指针本身或其副本),您就可以一切顺利。
关于c - 在实际指针的副本上使用 free() 是可以接受/正确的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43456215/