Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why malloc always return NULL

My dev environment is VS2008, DX9, Windows XP. I try to add protection handling to the out of memory case. When malloc return NULL, I would page some resource to disk, and release the resources in the memory.

But sometimes, malloc always return NULL, even if I release most of resources and process memory usage and VM size is only 800MB in task manager.

I think to use malloc to allocate 88 bytes should be fine, where process memory usage is only 800MB. But malloc always return NULL.

Could this be memory fragmentation? It doesn't look like that, since process memory usage is not too much.

alt text http://i.imagehost.org/0267/Snap2.jpg

like image 473
Buzz Avatar asked Mar 02 '10 06:03

Buzz


People also ask

How do I handle malloc returning NULL?

For some programs, simply aborting is the right thing to do. For some applications, the right thing to do is to shrink caches and try the malloc again. For some multithreaded programs, just waiting (to give other threads a chance to free memory) and retrying will work.

Do you have to malloc for NULL?

You need to malloc if you want to point to a new piece of memory. NULL means not pointing to any memory, so no. It's somewhat unusual to malloc() space for a pointer, whether NULL or otherwise.

Why does malloc fail?

So the first case of malloc() failing is when a memory request can not be satisfied because (1) there is not a usable block of memory on the list or heap of the C runtime and (2) when the C runtime memory management requested more memory from the operating system, the request was refused.

Does malloc set pointers NULL?

malloc tries to allocate a given number of bytes and returns a pointer to the first address of the allocated region. If malloc fails then a NULL pointer is returned. malloc doesn't initialize the allocated memory and reading them without initialization invokes undefined behaviour.


2 Answers

You mentioned memory fragmentation and that would certainly be my first guess. Try downloading this application. Its called Address Space Monitor, and should be able to show you if its a fragmentation issue.

like image 143
0xC0DEFACE Avatar answered Oct 09 '22 07:10

0xC0DEFACE


It could be virtual address space fragmentation. One way to check is to call HeapCompact(GetProcessHeap(), 0). If that frees up enough memory, then that's the likely cause.

Another similar cause would be launching from the debugger; that causes Windows to use the debug heap, which has really really bad memory behavior over a long period of time. To disable that behavior, set _NO_DEBUG_HEAP=1 in the environment and run.

like image 36
MSN Avatar answered Oct 09 '22 08:10

MSN