goldenmean
goldenmean

Reputation: 18996

calloc call fails and code crashes

I have a piece of C code as below which crashes at the calloc() call below:

... some code
free (ipl->fldptr);
ipl->fldptr = calloc (flds*4, sizeof(struct fldptr_type));
...some more code

I tried to gdb it and I get the below backtrace at crash:

Program received signal SIGSEGV, Segmentation fault.
0x0000003ade478f94 in _int_malloc () from /lib/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.7.el6.x86_64 libgcc-4.4.4-13.el6.x86_64 libstdc++-4.4.4-13.el6.x86_64
(gdb) bt
#0  0x0000003ade478f94 in _int_malloc () from /lib/libc.so.6
#1  0x0000003ade4796d8 in calloc () from /lib/libc.so.6
#2  0x0000000000daf00d in myfunction (ipl=0x106f75f0, flds=11)
    at myfile.c:1286

As part of debugging I do following on gdb prompt:

frame 2 to go to that user code stack frame and print values of variables(flds, pointers(ipl) and they seem ok. No NULL dereferencing apparently.

But still calloc() fails and it crashes there. This piece of code is executed multiple times successfully previously , but it crashes later when the application has run for some time. (Mem leak ?? tryint to get valgrind run on it, but it so happens that when running under valgrind memcheck tool, behaviour of my code crash is not repeatable)

I am looking for some pointers to help me debug and fix this.

Some info relevant - gcc: 4.4.4 . Red Hat Enterprise Linux server 6.0 64 bit Linux

Upvotes: 1

Views: 4555

Answers (1)

You probably have a corrupted heap, e.g. some memory which has been free-d too early (and still reused), or some buffer overflow (or invalid accesses like ptr[-3])

You should use valgrind to debug such issues.

You might also use Boehm's conservative garbage collector.

And you could also hunt such bugs manually, with gdb. Using the watch gdb command and disabling address space layout randomization should help.

I also suggest to always clear a pointer which you have free-d, so replace everywhere free(x) with free(x), x=NULL in your code (so if x gets incorrectly dereferenced, you'll get a SIGSEGV immediately).

You might also use a more recent version of GCC (current version is 4.7) with its stack protector feature. See this question.

Upvotes: 4

Related Questions