Lo, on Thursday, July 26, Shaul Karl did write: > Program received signal SIGSEGV, Segmentation fault. > 0x400af19e in malloc () from /lib/libc.so.6 > (gdb) > > > How can it be? If malloc can not allocate memory it should return a NULL > pointer. How can it Seg fault?
As Andrew Agno and Alan Shutko point out elsewhere in this thread, this is most likely due to an inadvertent corruption of the language runtime's accounting data in the heap (the area of memory managed by malloc() and free()). Typical causes: * freeing the same pointer twice * freeing a stack or global variable * in general, calling free() with any argument that was not returned by malloc(). * walking off the end of an array on the heap and clobbering some accounting data. * chasing a bogus pointer and clobbering some accounting data Rick Macdonald suggested that the first malloc may be returning 0, and the second would therefore attempt to set node->data to some other pointer, in spite of the fact that node is null. This could conceivably be possible (although, as you say, C's short-circuit boolean evaluation means it won't happen), but it wouldn't produce the results that you're seeing. The implementation of malloc() doesn't know anything about what you're going to do with the result. If, therefore, you tried to assign the second malloc's result to node->data when node is in fact null, you'd get a seg fault after you returned from the second malloc, not during it. The actual cause of the crash is likely to be quite distant (either in time, or in space, or both) from the failing malloc(), so figuring out exactly which malloc() crashes isn't likely to do you much good. As Andrew suggested, using a memory debugging tool like Electric Fence or Debauch may help you find the point in your program at which you smash the heap. Unfortunately, this may or may not be the location of the root error. While I'm a big fan of garbage collectors in general, I don't think that using one here will help you find the cause of this crash. When you've got a GC, you typically don't ever call free(), and a GC won't protect much against the last two causes I mentioned above. As a result, it will most likely hide the bug, or not affect it at all. These tend to be fairly nasty bugs to find and fix. Best of luck! Richard