Proteen Proteen - 1 year ago 112
C Question

strcmp crashes even though both strings are sane

I have a peculiar problem where my program crashes at strcmp.

Upon gdb core analysis I see that both the strings being checked are sane meaning their pointers are not NULL and they contain finite null terminated values.

However one of the strings is garbage (not the one the variable is intended to contain)

Leaving aside the fact that it is garbage, I really want to know why strcmp would crash for 2 sane strings ? What could be the possible causes of this ?

Thanks in advance!


An example,

a = strcmp(b,c);
(gdb) p b
$92 = 0x7f58d3a36b89 "H\205\300uRH\215}\320\350\a\300\361\377A\276"
(gdb) p c
$93 = 0x2041e48 "MAIN"

Answer Source

The values for b and c seem OK, but due to optimizations, especially around such functions as strcmp() that may undergo intense macro expansion, the actual values might not be available to the debugger.

The problem might be easy to spot in the source code, you should post the source to the offending function.

The value 0x7f58d3a36b89 printed by gdb for variable b is surprisingly large! You could try and modify your code this way:

static char bb = *b;
static char cc = *c;
a = strcmp(b, c);

Forcing an access to b and c before the strcmp() may move the crash up and let you verify if b is indeed what gdb prints it to be.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download