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

标签 c pointers malloc free

这是:

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 值(指针本身或其副本),您就可以一切顺利。

关于c - 在实际指针的副本上使用 free() 是可以接受/正确的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43456215/

相关文章:

c - 在 Assembly x86 中遍历二维数组

c++ - Linux 的 fork 函数与 Windows 的 CreateProcess 相比——复制了什么?

c - 调用函数时出现段错误

c - 如何在 C 中使用 char 指针初始化 char 数组

c++ - 如何找出代码的哪些部分创建了最多的虚拟内存?

c - 使用大量节点后 malloc 失败

c - 我已经在 C 中声明了一个大小为 1 的字符数组,但我已经读取了一个大小为 10 的字符串,但给定的代码工作得很好。

c++ - C 或 C++。如何比较给定 char * 指针的两个字符串?

C++ 通过引用传递 : how is the call stack used?

c - 将不同的结构传递给函数(使用 void *)