scanf dynamic allocation

Viewed 17279

For whatever reason the following code prints (null):

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *foo; 
    scanf("%ms", &foo);
    printf("%s", foo);
    free(foo);
}

I'm trying to allocate memory for a string dynamically but as I said earlier my program simply outputs (null). I worked around this by making a function using getche and realloc but it seems almost pointless due to the fact that I also had to program what would happen if the user entered backspace, tab, etc.. But as I said that is just a work around and I would rather know why the above code is not working...

Additional Information:

I am using the Pelles C IDE v7.00 and compiling with the C11 standard

6 Answers

There is an example in the man page for scanf/sscanf (page 3, from line 270-290) that states the following:

EXAMPLE

To use the dynamic allocation conversion specifier, specify m as a length modifier (thus %ms or %m[range]). The caller must free(3) the returned string, as in the following example:

char *p;
int n;

errno = 0;
n = scanf("%m[a-z]", &p);
if (n == 1) {
   printf("read: %s\n", p);
   free(p);
} else if (errno != 0) {
   perror("scanf");
} else {
   fprintf(stderr, "No matching characters\n");
}

As shown in the above example, it is necessary to call free(3) only if the scanf() call successfully read a string.

Source: SCANF(3) - Linux Programmer's Manual - GNU - 2013-01-30

Char* is a pointer, therefore when its passed as argument, there is no need for &pointer

Related