Good day! I'm a newbie in C. I'm trying to get an unlimited input from the user using malloc then printing the inputs after the user presses enter. My code works, but there's a warning that I don't know how to fix. Please help me. Thank you.
The given program allocates enough space to hold a pointer to a character; not enough space to read a line of user input. And, I don't see how eracav can preallocate space for "unlimited input from the user". In addition to that, eracav isn't checking the return value of malloc() to determine if space was allocated nor of fgets() to determine if an error or EOF has been encountered before a <newline> was found.
To do what needs to be done, eracav will need much more complicated logic with a loop calling fgets() and realloc() to increase the input buffer size until a <newline> or EOF has been copied into the growing buffer.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main () {
char* pointer = malloc(sizeof(char*) * 4096);
if(pointer==NULL)
{
perror("Cannot allocate memory");
exit(1);
}
fgets(pointer, 4096, stdin);
puts(pointer);
puts("\n"); // in case the user enters more than 4095 chars and you lose the trailing \n
free(pointer);
return 0;
}
You have to set an arbitrary limit, I chose 4096.
Best practice if you malloc:
check the return code from the malloc call, and handle any errors.
free any memory you do not need anymore.
And. You code did not work, it had undefined behavior. A successful compile in C means no warnings, no errors, no dereference of undefined or possibly NULL pointers.
char * is 'pointer to characters', you don't want to allocate pointers, you want to allocate characters. So, sizeof(char) would make more sense than sizeof(char *).