Hi ich versuche zu lesen Benutzereingabe von "unbegrenzte" Länge in ein Char-Array. Es funktioniert gut für kürzere Strings, aber für mehr als 30 Zeichen stürzt das Programm ab. Warum passiert das und wie kann ich das beheben?C: String in dynamisches Array lesen
#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 (Eingang, (sizeof (char))); // reserviere mehr Speicher' Dieser Kommentar ist falsch. Durch die Neuzuweisung von 1 Byte zu 1 Byte wird kein Speicher mehr zugewiesen. Das zu ignorieren, was von 'realloc()' zurückgegeben wird, ist ebenfalls schlecht. – MikeCAT
Vergessen Sie auch nicht, Platz für den Terminator zu reservieren. – MikeCAT
Das scheint zu funktionieren: 'realloc (input, (sizeof (char) * length + 1)); ' – t1msu