【发布时间】:2022-01-05 02:01:18
【问题描述】:
您好,我正在尝试将“无限”长度的用户输入读入 char 数组。它适用于较短的字符串,但对于超过 30 个字符,程序会崩溃。为什么会发生这种情况,我该如何解决?
#include <stdio.h>
#include <stdlib.h>
char* read_string_from_terminal()//reads a string of variable length and returns a pointer to it
{
int length = 0; //counts number of characters
char c; //holds last read character
char *input;
input = (char *) malloc(sizeof(char)); //Allocate initial memory
if(input == NULL) //Fail if allocating of memory not possible
{
printf("Could not allocate memory!");
exit(EXIT_FAILURE);
}
while((c = getchar()) != '\n') //until end of line
{
realloc(input, (sizeof(char))); //allocate more memory
input[length++] = c; //save entered character
}
input[length] = '\0'; //add terminator
return input;
}
int main()
{
printf("Hello world!\n");
char* input;
printf("Input string, finish with Enter\n");
input = read_string_from_terminal();
printf("Output \n %s", input);
return EXIT_SUCCESS;
}
【问题讨论】:
-
realloc(input, (sizeof(char))); //allocate more memory这个评论是错误的。将 1 个字节重新分配到 1 个字节不会再分配内存。忽略从realloc()返回的内容也很糟糕。 -
另外别忘了给终结者分配空间。
-
这似乎有效:
realloc(input, (sizeof(char)*length+1)); -
@t1msu 这似乎有效:
realloc(input, (sizeof(char)*length+1));你将返回的指向分配给什么?此外,getchar()返回int,而不是char。 -
不要强制转换 malloc 和好友的返回值。
标签: c