简体   繁体   中英

"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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM