For the scanf
call, text
parameter, you do not allocate any memory. You also do not initialize the variable to a value. This results in scanf
writing to random memory, which causes your segmentation fault.
To fix this issue you need to allocate a buffer of a reasonable size:
char* text = malloc(1024);
1024
is the maximum size that you expect the input data to be. This, however, still leaves the code vulnerable to buffer overflows. To prevent buffer overflows you can inform scanf
that text
is of a certain size; look for the answers here
If you do not want to allocate the memory yourself, scanf
can do it for you:
Note that the POSIX 2008 (2013) version of the
scanf()
family of functions supports a format modifier m
(an
assignment-allocation character) for string inputs (%s
, %c
, %[
).
Instead of taking a char *
argument, it takes a char **
argument,
and it allocates the necessary space for the value it reads:
char *buffer = 0;
if (sscanf(data, "%ms", &buffer) == 1)
{
printf("String is: <<%s>>\n", buffer);
free(buffer);
}
If the sscanf()
function fails to satisfy all the conversion
specifications, then all the memory it allocated for %ms
-like
conversions is freed before the function returns.