嗨即時嘗試讀取「無限」長度的用戶輸入到char數組。它適用於較短的字符串,但超過30個字符左右的程序崩潰。爲什麼會發生這種情況,我該如何解決這個問題?C:將字符串讀入動態數組
#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(輸入,(的sizeof(char)的)); //分配更多內存'這個評論是錯誤的。將1個字節重新分配給1個字節不會再分配內存。忽略從'realloc()'返回的內容也是不好的。 – MikeCAT
另外不要忘記爲終結者分配空間。 – MikeCAT
這似乎工作:'realloc(input,(sizeof(char)* length + 1)); ' – t1msu