Segmentation Fault during malloc() with gdb

From Higher Intellect Wiki
Jump to: navigation, search

I am using IRIX Release 6.5 UNIX/SGI. I write code in C++ and compile it using g++. I then run it in debug mode using gdb. For some reason, the following call

unsigned long dwRows=236;
float   **fppBuffer=NULL;
fppBuffer=(float **)malloc(dwRows*sizeof(float *));

results in the following error message.

Program received signal SIGSEGV, Segmentation fault.
0xfa2efcc in realfree () at malloc.c:316
malloc.c:316: No such file or directory.
Current language:  auto; currently c

dwRows*sizeof(float *) has the value 944.

Does anyone know what's causing this problem? Any help would be greatly appreciated.

Response

take out the (float **) cast. it can only hide errors, and if you #include <stdlib.h> (which you should anyway), you don't need the cast.

i don't see anything (else) wrong with this malloc call. you must have trashed the memory allocation scheme at some point earlier in your program -- by writing past the end of an array, or free'ing a bad pointer, or free'ing the same pointer twice. once you do this, all bets are off and any call to malloc, realloc, free etc. can cause a crash.

here is the related FAQ from comp.lang.c:

7.19:   My program is crashing, apparently somewhere down inside malloc,
        but I can't see anything wrong with it.  Is there a bug in
        malloc()?

A:      It is unfortunately very easy to corrupt malloc's internal data
        structures, and the resulting problems can be stubborn.  The
        most common source of problems is writing more to a malloc'ed
        region than it was allocated to hold; a particularly common bug
        is to malloc(strlen(s)) instead of strlen(s) + 1.  Other
        problems may involve using pointers to memory that has been
        freed, freeing pointers twice, freeing pointers not obtained
        from malloc, or trying to realloc a null pointer (see question
        7.30).

        See also questions 7.26, 16.8, and 18.2.

Crashing in malloc or free is an indication that you've corrupted the heap by the usual memory mismanagement (writing outside of allocated blocks, double freeing, etc.). In other words, the cause of the bug is almost certainly not on the line in question.

Although this may not be the SGI libc malloc, from the NOTES of man malloc:

A SEGV or Bus Error inside the malloc routine is almost certainly caused by a previous memory overwrite by the user. This is a delayed error which is caused by a previous overwrite of unallocated memory and is not a bug in malloc itself.

There *are* of course a number of tools to trace such things (Purify is one that springs to mind, but it's no exactly free).



Share your opinion