PDA

View Full Version : realloc fixes program crash


hunguptodry
03-20-2007, 12:59 AM
1) i allocate some memory in my program with a call to malloc ...
cn->cp = (cinst *) malloc(n*sizeof(cinst));
program crashes in fscanf some time later.

2) i replace the single malloc call with 2 calls ...
cn->cp = (cinst *) malloc(100*sizeof(cinst));
cn->cp = realloc(cn->cp,n*sizeof(cinst));
the problem goes away.

3) the debugger is no help here.

4) r there any tools i can use to track down such problems?

hovermonkey
03-20-2007, 06:24 AM
Try posting the code around the fscanf as this is probably the culprit.

SigKILL
03-20-2007, 11:10 AM
3) A debugger always helps.
4) A debugger is 'the' tool for these things. Or you could use something like boundsChecker, which would be overkill IMHO.

The problem is obviously not in the code you posted, so you should provide us with more details. AFAIK, realloc() calls malloc() on most compilers so your 2) is unnecessary. If you tend to write outside allocated memory in debug mode, the heap check tends to assert() at seemingly random positions (which could be your problem).

EDIT: Fixed bad sentence ( I do not think boundsChecker is the worst....).

Sol_HSA
03-20-2007, 12:15 PM
Yes, sounds like a memory trashing problem. If you have money to throw at the problem, get boundschecker or purify - if you're on linux, electric fence is a free library that might help.

If the above is not a solution, you can try allocating, say, 2k more than you need, fill it with a known value (say, 0xfc) and use the memory in the middle. Track this in debugger memory view, and you should see if something writes outside the allocated range. You can also set memory modify breakpoints.

Nick
03-20-2007, 05:11 PM
If you're using C++, look for Paul Nettle's Memory Manager (MMGR). Saved me a couple headaches...

juhnu
03-20-2007, 08:14 PM
Yes, sounds like a memory trashing problem. If you have money to throw at the problem, get boundschecker or purify

...and GlowCode

monjardin
03-20-2007, 09:47 PM
Is there another source for the mmgr.zip (ftp://ftp.flipcode.com/code/mmgr.zip) file? The link from Nettle's flipcode article (http://www.flipcode.org/cgi-bin/fcarticles.cgi?show=64444) seems to be dead.

Dia Kharrat
03-21-2007, 12:07 AM
Here's the official source:

http://www.paulnettle.com/pub/FluidStudios/MemoryManagers/Fluid_Studios_Memory_Manager.zip

I've personally used it as well in the past, and it does a pretty good job.