From: j DOT aldrich6 AT genie DOT com Message-Id: <199605250547.AA135513228@relay1.geis.com> Date: Sat, 25 May 96 05:38:00 UTC 0000 To: djgpp AT delorie DOT com Mime-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=us-ascii Subject: Re: Trapping failed malloc cal Reply to message 9858534 from MALCOLM AT MANAW on 05/24/96 4:39AM > I am wondering if there is an easy way of trapping failed malloc and >new calls within a program. At present the program will just exit with >a stack trace that often hides the fact that the program is simply >running out of memory (eg a memory leak bug maybe). I would like to be >able to trap a failed call to malloc (or new) and exit gracefully with >a message about running out of memory. Lemme guess... you taught yourself C? Otherwise, you'd know that the entire malloc() family of functions all return a NULL pointer if they are unable to allocate memory. So... foo *p; if ( ( foo = (foo *) malloc( sizeof(foo) ) ) == NULL ) { fprintf( stderr, "Out of memory.\n" ); exit( 1 ); } > Also if anyone has any better malloc for wide ranging sizes than the >standard malloc I would be interested. One particular program I've >written mallocs blocks that are from between 100b and 4Mb in size >(approx) and the normal malloc seems to use more memory than it needs. >If you know of one then please e-mail me about it. AFAIK, malloc under DPMI allocates memory in blocks of varying sizes; asking for 101K might get you 104K in reality. Don't quote me on this, though. Also, programs running with DPMI and virtual memory have no reliable way to detect free memory remaining both because of paging and because the DPMI host recycles used memory instead of permanently freeing it. If you are depending on the available_physical_memory and available_virtual_memory functions to tell you how much memory you are actually using, you will not get the results you expect. The best you can hope for is that the sum of those numbers, subtracted from what go32-v2 displays, equals the maximum amount of memory your program ever uses. One thing to be careful of is not to allocate too many individual chunks of memory at any given time. CWSDPMI has a bug wherein it will run out of its internal heap if you allocate more than 1000 or so blocks of memory. There's a "heap fix" program that corrects the problem at the cost of increasing the size of the CWSDPMI image; look in the FAQ for its location.