如果Realloc返回null,我必须释放旧内存吗?
因此,我知道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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果在此代码段中,
函数
realloc
将返回null,则在这种情况下,早期分配的内存将无法释放。因此,在这种情况下,程序或函数的行为应取决于上下文。您可以释放先前分配的内存
,或者继续考虑
realloc
失败的先前分配的内存。If in this code snippet
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
or continue to deal with the previously allocated memory taking into account that
realloc
failed.