gpt4 book ai didi

c - 如果 realloc 返回 NULL,我是否必须释放旧内存?

转载 作者:行者123 更新时间:2023-12-05 02:28:09 26 4
gpt4 key购买 nike

所以我知道 realloc() 可以遵循两种方式。第一种方法是在新地址分配内存并释放旧内存。第二种方法是在同一地址分配内存,这样您只需要释放该地址。所以在这两种方式中,你只需要释放 realloc() 分配的地址。但是,如果 realloc() 返回 NULL 会发生什么,我是否必须像这样释放旧内存? :

//so in the first way, as b would be another address, a would be freed and if b is NULL it is no necessary to free it. But, if it follows second way, b will be same address as a and if it is NULL, I need to free old memory (a), right? 
int *a = (int*)malloc(sizeof(int));
int *b = (int*)realloc(a,sizeof(int)*3);

if(!b){
free(a);
}

最佳答案

如果在这段代码中

int *a = (int*)malloc(sizeof(int));
int *b = (int*)realloc(a,sizeof(int)*3);

函数 realloc 将返回 NULL,那么在这种情况下,早期分配的内存将不会被释放。

所以程序或函数在这种情况下的行为取决于上下文。您可以释放之前分配的内存

free( a );

或者考虑到 realloc 失败,继续处理之前分配的内存。

关于c - 如果 realloc 返回 NULL,我是否必须释放旧内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72749177/

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