cpointersscanfbus-error

Scanf fails with bus error


I'm playing with C and I've run into this error:

#include <stdio.h>
int main ()
{
 char* foo;
 scanf("%s", foo);
 printf("entered %s", foo);
 return 0;
}

scanf takes pointer, foo is pointer, yet I get bus error. How can I make it work?


Solution

  • You never initialize foo, so it points to a more or less random location in memory. Either allocate it on the stack.

    char foo[10];
    

    Or malloc it on the heap:

    char *foo = (char *)malloc(10 * sizeof(char));
    

    But if you malloc, don't forget to free().

    And watch out for buffer overflows; if something takes in a buffer but no maximum size, be very careful. You can specify a maximum length for scanf by doing %9s, for instance. scanf will not account for the terminating null, though, so you need to pass one less than the length of your buffer.