簡體   English   中英

分段故障(核心轉儲)

[英]segmentation fault (core dump)

當我嘗試運行它時出現分段錯誤(核心轉儲)。 它可以完美地編譯,但是出現錯誤,我也不知道為什么。 我試圖以所有可能的方式編輯代碼,但仍然收到此錯誤。 我已經沒有主意了。 任何幫助都會很棒。 謝謝!

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

編譯調試信息:

> gcc -o myprog myprog.c -ggdb

在調試器中運行

> gdb myprog
(gdb) run

調試器告訴您段發生在哪里:

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 regcrc_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 */

regcrc_messageNULL 這將傳遞到crc_byte ,然后傳遞到crc_bit 然后使用訪問地址為NULL的位置。

對我來說,您的分段錯誤問題來自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;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM