分段故障(核心转储)
当我尝试运行它时,我收到了分段错误(核心转储)。 它完美编译,但我得到错误,我不知道为什么。 我试图以所有可能的方式编辑我的代码,但我仍然收到此错误。 我已经没有想法了。 任何帮助都会很棒。 谢谢!
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; }
对我来说,你的分段错误问题来自reg指针,它是NULL。 这意味着您将修改位于零地址的unisgned hsort值。 在大多数操作系统上,这是不允许的。
你为什么不做以下事情?
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;
}
编译调试信息:
> gcc -o myprog myprog.c -ggdb
在调试器中运行
> gdb myprog (gdb) run
调试器会告诉您segfault发生的位置:
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;
注意reg是0(即NULL),你取消引用它。
您正在将NULL
reg
传递给crc_byte()
,它将它传递给crc_bit()
,然后crc_bit()
尝试取消引用它。
像这样更改function:
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 */
reg
在crc_message
为NULL
。 这被传递给crc_byte
,它被传递给crc_bit
。 然后使用访问地址为NULL
的位置。