0

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;
}
2
  • 1
    Please have a look at this: stackoverflow.com/questions/5115613/core-dump-file-analysis Commented Feb 10, 2014 at 7:30
  • Downvoted because answers are all grasping for straws. The posted code is nowhere near complete enough to know why a seg fault is occurring. People answering can only guess. Commented Aug 16, 2023 at 17:25

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

You are passing a NULL reg into crc_byte(), which passes it to crc_bit(), which then tries to dereference it.

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(&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 */

Comments

0

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.

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(&reg, key, next_byte);
}

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

return reg;

}

Comments

0

reg is NULL in crc_message. This gets passed on to crc_byte which gets passed on to crc_bit. Then use access a location which has an address NULL.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.