分段故障(核心转储)

时间:2014-02-10 07:26:44

标签: c

当我尝试运行它时,我收到了分段错误(核心转储)。它完美编译,但我得到错误,我不知道为什么。我试图以所有可能的方式编辑我的代码,但我仍然收到此错误。我已经没有想法了。任何帮助都会很棒。谢谢!

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

4 个答案:

答案 0 :(得分:5)

编译调试信息:

> 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),您可以取消引用它。

答案 1 :(得分:2)

您正在将NULL reg传递给crc_byte(),然后将其传递给crc_bit(),然后尝试取消引用它。

更改功能如下:

unsigned short reg = 0;  /* replace 0 with whatever value is appropriate */
...

for (byte = 0; byte < num_bytes; byte++){
    ...
    crc_byte(&reg, key, next_byte);  /* added the ampersand */
}

for (i = 0; i < 16; i++){
    crc_bit(&reg, key, 0);  /* added the ampersand */
}

return reg;  /* removed the asterisk */

答案 2 :(得分:0)

reg中{p> NULLcrc_message。这会传递给crc_byte,并传递给crc_bit。然后使用访问地址为NULL的位置。

答案 3 :(得分:0)

对我来说,您的分段错误问题来自reg指针,它是NULL。 这意味着您将修改位于零地址的未分配的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(&reg, key, next_byte);
}

for (i = 0; i < 16; i++){
    crc_bit(&reg, key, 0);
}

return reg;

}

相关问题