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;
}
user3291818
  • 203
  • 1
  • 3
  • 11
  • 1
    Please have a look at this: http://stackoverflow.com/questions/5115613/core-dump-file-analysis – Axel Feb 10 '14 at 07: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. – shawn1874 Aug 16 '23 at 17:25

4 Answers4

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.

ooga
  • 15,423
  • 2
  • 20
  • 21
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 */
NPE
  • 486,780
  • 108
  • 951
  • 1,012
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.

ssm
  • 5,277
  • 1
  • 24
  • 42
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;

}

nomoney29
  • 116
  • 1
  • 1
  • 5