简体   繁体   English

“总线错误”和“分段错误”,最小代码包含 C 中的结构

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

I wrote a minimal C code as follows:我写了一个最小的 C 代码如下:

#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.当我将上述代码放入 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).当我注释掉第一行 main (结构的 instatioation)时它工作正常。 Any explanation would be appriciated.任何解释都会被应用。

tmp is a pointer that isn't pointing anywhere. tmp是一个不指向任何地方的指针。 It is uninitialized , meaning its value is indeterminate .它是未初始化的,意味着它的值是不确定的。 So when you pass this pointer to scanf , it attempt to dereference this invalid pointer.因此,当您将此指针传递给scanf时,它会尝试取消引用此无效指针。 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:tmp更改为一个足以容纳所需值的数组,并确保在scanf格式中指定最大字段大小:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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