什么是realloc的(失败时)的正确用法,并返回NULL? [英] What is the correct usage of realloc() when it fails and returns NULL?

查看:919
本文介绍了什么是realloc的(失败时)的正确用法,并返回NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能总结一下就是的正确用法的realloc()

你是做什么的时候的realloc()失败?

What do you do when realloc() fails?

从我迄今所看到的,看来,如果的realloc()失败,你必须免费()旧指针。是真的吗?

From what I have seen so far, it seems that if realloc() fails, you have to free() old pointer. Is that true?

下面是一个例子:

   1.  char *ptr = malloc(sizeof(*ptr) * 50);
   2.  ...
   3.  char *new_ptr = realloc(ptr, sizeof(*new_ptr) * 60);
   4.  if (!new_ptr) {
   5.      free(ptr);
   6.      return NULL;
   7.  }

假设的realloc()失败就行 3 。我是 5 免费() ING PTR

Suppose realloc() fails on line 3. Am I doing the right thing on line 5 by free()ing ptr?

谢谢,博大Cydo。

推荐答案

://www.c- faq.com/malloc/realloc.html

如果realloc的不能找到足够的空间可言,它返回一个空指针,并且留下previous区域分配的。

If realloc cannot find enough space at all, it returns a null pointer, and leaves the previous region allocated.

因此​​,你的确需要仍然是免费的previously分配的内存。

Therefore you would indeed need to free the previously allocated memory still.

这篇关于什么是realloc的(失败时)的正确用法,并返回NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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