Ç - 如果使用realloc的是免费的必要吗? [英] C - If realloc is used is free necessary?

查看:154
本文介绍了Ç - 如果使用realloc的是免费的必要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用realloc的是内存自动释放?或者是否有必要使用自由搭配的realloc?以下哪项是正确的?

  //现状的
ptr1的=的realloc(ptr1的,3 * sizeof的(INT));//状况乙
ptr1的=的realloc(PTR2,3 * sizeof的(INT));
免费(ptr1的);
ptr1的= PTR2;


解决方案

也不是正确的。 realloc的()可以返回一个指向新分配的内存或NULL的错误。你应该做的是检查返回值:

  ptr1的=的realloc(PTR2,3 * sizeof的(INT));
如果(!ptr1的){
    / *做的东西在这里处理失败* /
    / * PTR2仍然指向分配的内存,所以你可能需要释放(PTR2)这里* /
}/ *成功! ptr1的现指向分配的内存和PTR2已经被释放* /
免费(ptr1的);

When using realloc is the memory automatically freed? Or is it necessary to use free with realloc? Which of the following is correct?

//Situation A
ptr1 = realloc(ptr1, 3 * sizeof(int));

//Situation B
ptr1 = realloc(ptr2, 3 * sizeof(int));
free(ptr1);
ptr1 = ptr2;

解决方案

Neither is correct. realloc() can return a pointer to newly allocated memory or NULL on error. What you should do is check the return value:

ptr1 = realloc(ptr2, 3 * sizeof(int));
if (!ptr1) {
    /* Do something here to handle the failure */
    /* ptr2 is still pointing to allocated memory, so you may need to free(ptr2) here */
}

/* Success! ptr1 is now pointing to allocated memory and ptr2 was deallocated already */
free(ptr1);

这篇关于Ç - 如果使用realloc的是免费的必要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆