cpointerssegmentation-faultscanfbus-error

"bus error" and "Segmentation fault" with a minimal code containing a struct in C


I wrote a minimal C code as follows:

#include <stdio.h>

struct Books {
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
};

int main() {
   struct Books Book1;

   char *tmp;
   int counter=0;

   scanf("%s", tmp);
   return 0;
}

When I compile and run the above code, after providing an input, I get the following error:

❯ gcc main.c
❯ ./a.out
e
[1]    86266 bus error  ./a.out
❯ vim main.c
$

I get a "Segmentation fault" when I put the above code in a function.

I have no idea what's wrong with this code. It works fine when I comment out first line main (the struct's instatioation). Any explanation would be appriciated.


Solution

  • tmp is a pointer that isn't pointing anywhere. It is uninitialized, meaning its value is indeterminate. So when you pass this pointer to scanf, it attempt to dereference this invalid pointer. This invokes undefined behavior which in your case causes the program to crash.

    Change tmp into an array big enough to hold the value you want, and be sure to specify a maximum field size in your scanf format:

    char tmp[50];
    scanf("%49s", tmp);