Page 1 of 1

Should I use HeapAlloc or malloc/new?

Posted: Fri Apr 29, 2011 10:53 pm
by Rapid Cube
As I understand it, malloc and new both call HeapAlloc internally. The program I'm working on at the moment is a win32 application, so portability isn't really an issue. I'm not sure what the overhead in malloc and new does and if its really necessary or not. So if anyone knows please tell me.

Re: Should I use HeapAlloc or malloc/new?

Posted: Sat Apr 30, 2011 12:01 am
by short
Depends. If your using C++ libraries use new. If your using C libraries use malloc.

I would go into more detail but google a mouse click away.

Re: Should I use HeapAlloc or malloc/new?

Posted: Mon May 02, 2011 6:54 pm
by Falco Girgis
I have never even heard of anybody bypassing malloc() or new on a win32 platform and just directly calling heapAlloc(). Either the overhead is absolutely tiny, or (more than likely) the overhead is inlined and optimized away by the compiler, so it's free. I wouldn't bother.

Re: Should I use HeapAlloc or malloc/new?

Posted: Tue May 03, 2011 12:43 pm
by Rapid Cube
I looked through malloc.c and the overhead is really tiny. First it checks to see if you're trying to allocate more memory than the system could possibly allow. Then it checks to see if _crtheap (which I imagine is a handle to the default process heap) is null. After that it calls HeapAlloc and if that succeeds the function returns. You can supply your own memory handling function that's called in the event that HeapAlloc fails. This function is called until HeapAlloc can succeed or your function returns 0.
If anyone wants to try to do this then first call _set_new_mode(1), then call _set_new_handler passing a function like this:
int NewHandler(size_t size). To stop malloc from calling your new handler function call _set_new_mode(0). To clear the new handler call _set_new_handler(0).

Re: Should I use HeapAlloc or malloc/new?

Posted: Tue May 03, 2011 3:19 pm
by Falco Girgis
Damn, that's good to know. Thanks for reporting the find. :)

Re: Should I use HeapAlloc or malloc/new?

Posted: Wed May 04, 2011 2:03 pm
by Rapid Cube
It seems you would mainly use win32's native heap functions for dealing with user created heaps.