如果Realloc返回null,我必须释放旧内存吗?

发布于 2025-02-10 21:28:27 字数 561 浏览 2 评论 0原文

因此,我知道realloc()可以遵循2种方法。第一种方法是在新地址中分配内存并释放旧内存。第二种方法是在同一地址中分配内存,因此您只需要释放该地址即可。因此,从这两种方面来说,您只需要释放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);
}

So I know that realloc() can follow 2 ways. The first way is allocating memory in a new address and freeing old memory. Second way is allocating memory in the same address so that you will only need to free that address. So in both ways, you only have to free the address that realloc() allocates. But, what would happen if realloc() returned NULL, do I have to free old memory like this? :

//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);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小梨窩很甜 2025-02-17 21:28:27

如果在此代码段中,

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

函数realloc将返回null,则在这种情况下,早期分配的内存将无法释放。

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

free( a );

,或者继续考虑realloc失败的先前分配的内存。

If in this code snippet

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

the function realloc will return NULL then in this case the early allocated memory will not be freed.

So how the program or the function should behave in this case depends on the context. You can free the previously allocated memory

free( a );

or continue to deal with the previously allocated memory taking into account that realloc failed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文