What is XMALLOC and how it compares with malloc?
Rob Landley
rob at landley.net
Thu May 3 14:54:08 PDT 2007
On Thursday 03 May 2007 3:42 pm, ehuang at ix.netcom.com wrote:
> rdesktop.c:/* malloc; exit if out of memory */
> rdesktop.c:void *xmalloc(int size)
Note that the reason this is so common is that malloc returning nonzero
doesn't tell you a darn thing about whether or not the allocation actually
succeeded on any modern system with virtual memory.
What malloc does is allocates virtual memory and populates it with duplicate
copy-on-write mappings of the zero page. Attempts to actually write to it
break the COW and allocate physical pages, so the malloc is only going to
return NULL if it ran out of _virtual_ memory (which happens on 32-bit
systems, but is much less common and not really something you can do anything
useful about).
When the system truly runs out of memory first it'll swap thrash for a bit
(true even if you have no swap file, because mmap()ed files can flush the
file contents back to disk to free up the physical pages and both executables
and shared libraries are mmap()ed, and then it'll either trigger the out of
memory killer. (If you've disabled the OOM killer it'll instead freeze the
entire system solid, which some people do because they think that hanging the
entire system is an improvement over killing individual processes in an
emergency because killing processes is bad, m'kay.)
So the actual physical allocation happens when writing to memory, not via
malloc(), and the OOM killer steps in and goes "bang" rather than giving you
ar eturn value you can check. Which causes the same sort of exit() that
xmalloc() would.
Rob
More information about the uClibc
mailing list