Reputation: 340
On start up my application will crash about %50 of the time with a segmentation fault at the following line of code:
float** temp = new float*[map_size];
The value of map_size is 513.
This crass never occurs in debug mode. The application is fairly large now at 10,000 lines of code and has multiple threads running so I doubt posting any additional code will be of use. (I'm not sure what to post really)
Since this line of code is fairly straight forward I'm guessing that my error is elsewhere. My best guess would be that somewhere else my program is overreaching allocated memory and then when I try to allocate more occasionally it clashes and causes the fault. Is this a possible scenario?
What sort of behaviour could cause a segmentation fault at memory allocation? And how can I narrow down where this is occurring in my code?
Upvotes: 0
Views: 116
Reputation: 283644
Crashes calling memory allocation function are almost always due to corruption of the heap.
Think about how a memory allocation function works. It first checks a list of previously freed blocks to see if there's one of an appropriate size, and if none is found it asks for a new block from the OS.
If some other code has trashed the heap's internal pointers by writing beyond the bounds of some other dynamically allocated object, then when the memory allocation function used by ::operator new
tries to walk the heap, it will use a wild pointer and crash.
The crash occurs here, but the memory corruption occurred earlier, and could literally be anywhere in your program that works with dynamically allocated objects. It doesn't even have to be where the allocation or deallocation takes place.
Check whether your compiler provides "malloc debugging" which adds extra canary fields to the heap metadata surrounding dynamic allocations, in order to detect writes beyond the bounds. Something like Electric Fence (free!) can also help, by arranging for an unreachable page of memory to separate the metadata from every object, so the MMU traps the bounds error. Or a runtime bounds checker along the lines of Rational Purify (really really expensive).
Upvotes: 4