c - C 中的 Realloc 和 NULL 指针

标签 c realloc

为什么这个程序不适用于所有输入? (读入输入并按相反顺序打印输出) Xcode6 生成错误消息: hw5(14536,0x7fff7c23f310) malloc: * 对象 0x100103aa0 错误:未分配重新分配的指针 * 在malloc_error_break 设置断点调试 不幸的是我不明白这一点。

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char *input;
  unsigned long long index;
  input = malloc(1);

  for (index = 0; (input[index] = getchar()) != EOF; index++)
  {
    if (input == NULL)
    {
      free(input);
      printf("Error: Out of memory!\n");
      return 0;
    }
    realloc(input, index + 2);
  }

  for (index = index - 1; index != 0; index--)
  {
    putchar(input[index]);
  }
  printf("\n");

  free(input);

  return 0;
}

最佳答案

realloc() 返回指向新对象的指针。我正在使用临时变量,因为如果 realloc() 无法重新分配内存,则会返回 NULL 并且 input 仍然有效。

char* temp = realloc(input, index + 2);
if( !temp )
{
    //deal with error ...
}

input = temp ;

关于c - C 中的 Realloc 和 NULL 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27016745/

相关文章:

将 C 字符串转换为 Go 字符串,无需 CGO

c - 埃尔卡皮坦 : Undefined symbol "start" whenever I compile a C program

c++ - 如何消除程序中的链接器错误?

c - 我在 c 中的 realloc() 做错了什么?

使用 realloc 将 CSV 文件保存在数组中

c、malloc 和 realloc 结构体数组

c - 如何为每个 posix 操作系统编译 GnuTLS

c - 为什么指针只递增一次

c - 当我为内部有 union 的嵌套结构分配和释放内存时出了什么问题

c - realloc 失败的可能性有多大?