C语言 分段错误(核心转储)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21671272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
segmentation fault (core dump)
提问by user3291818
I'm getting a segmentation error (core dump) when I try to run this. It compiles perfectly but I get the error, and I don't know why. I've tried to edit my code in all possible ways, but am still getting this error. I'm out of ideas already. Any help would be great. Thanks!
当我尝试运行它时,出现分段错误(核心转储)。它编译完美,但我收到错误,我不知道为什么。我已尝试以所有可能的方式编辑我的代码,但仍然收到此错误。我已经没有想法了。任何帮助都会很棒。谢谢!
unsigned short *reg = NULL;
int byte;
int i;
for (byte = 0; byte < num_bytes; byte++){
unsigned int next_byte = (unsigned int) message[byte];
crc_byte(reg, key, next_byte);
}
for (i = 0; i < 16; i++){
crc_bit(reg, key, 0);
}
return *reg;
}
采纳答案by nomoney29
For me, your segmentation fault problem comes from the reg pointer which is NULL. This means that you will modify an unisgned hsort value located at address zero. On most operating systems, this is not allowed.
对我来说,您的分段错误问题来自为 NULL 的 reg 指针。这意味着您将修改位于地址零的未指定 hsort 值。在大多数操作系统上,这是不允许的。
Why don't you do the following thing ?
你为什么不做下面的事情?
unsigned short crc_message(unsigned int key, char *message, int num_bytes) {
unsigned short reg;
int byte;
int i;
for (byte = 0; byte < num_bytes; byte++){
unsigned int next_byte = (unsigned int) message[byte];
crc_byte(®, key, next_byte);
}
for (i = 0; i < 16; i++){
crc_bit(®, key, 0);
}
return reg;
}
}
回答by ooga
Compile with debugging info:
使用调试信息编译:
> gcc -o myprog myprog.c -ggdb
Run in a debugger
在调试器中运行
> gdb myprog
(gdb) run
Debugger tells you where the segfault occurred:
调试器会告诉您段错误发生的位置:
Program received signal SIGSEGV, Segmentation fault.
0x0040133d in crc_bit (reg=0x0, key=12345, next_bit=0) at rrr.c:4
4 unsigned int msb = (*reg >> (sizeof(*reg)-1)) & 1;
Note that reg is 0 (i.e., NULL) and you dereference it.
请注意,reg 为 0(即 NULL)并且您取消引用它。
回答by NPE
You are passing a NULLreginto crc_byte(), which passes it to crc_bit(), which then tries to dereference it.
您正在传递一个NULLreginto crc_byte(),它将它传递给crc_bit(),然后尝试取消引用它。
Change the function like so:
像这样更改函数:
unsigned short reg = 0; /* replace 0 with whatever value is appropriate */
...
for (byte = 0; byte < num_bytes; byte++){
...
crc_byte(®, key, next_byte); /* added the ampersand */
}
for (i = 0; i < 16; i++){
crc_bit(®, key, 0); /* added the ampersand */
}
return reg; /* removed the asterisk */
回答by ssm
regis NULLin crc_message. This gets passed on to crc_bytewhich gets passed on to crc_bit. Then use access a location which has an address NULL.
reg是NULL在crc_message。这被传递给crc_byte哪个被传递给crc_bit。然后使用访问具有地址的位置NULL。

