为什么这个程序不适用于所有输入? (读入输入并按相反顺序打印输出) 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/