I want to read the input of a user and save it. What i have now does work but i need to know if its legit (following ansi standard - c90) that scanf is first assigning the variable "length" before it allocates memory for the input, or if its just a quirk of the compiler.
#include <stdio.h>
int main()
{
char* text;
int length = 0;
scanf("%s%n", text = malloc(length+1), &length);
printf("%s", text);
return 0;
}
This will not work as you expect.
At the time you call malloc
, length
still has the value 0, so you're only allocating one byte. length
isn't updated until after scanf
returns. So any non-empty string will write past the bounds of the allocated buffer, invoking undefined behavior.
While not exactly the same, what you can do is use getline
, assuming you're running on a POSIX system such as Linux. This function reads a line of text (including the newline) and allocates space for that line.
char *text = NULL;
size_t n = 0;
ssite_t rval = getline(&text, &n, stdin);
if (rval == -1) {
perror("getline failed");
} else {
printf("%s", text);
}
free(text);