gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:59 25 4
gpt4 key购买 nike

这是:

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() 或 family 返回的相同 ptr 值(指针本身或其副本),您一切顺利。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com