Malloc Flavors

malloc is the workhorse of dynamic memory allocation in C and ultimately many other languages.

malloc is the function name and ultimately it specifies a contract, but implementations can and do vary. Today, I thought I'd write a bit about the various implementations you might run into by default, and some customized or honorable mentions worth calling out.

Linux

malloc is typically provided via the C runtime library in glibc, with the OS providing brk and mmap (sbrk being a library function around brk on Linux).

The glibc wiki points out it's derived from ptmalloc, in turn derived from dlmalloc. I like the details in 'what is a chunk' which can come in handy when spelunking around memory areas.

Windows

malloc is typically provided via the C runtime library in MSVCRT, with the OS providing HeapAlloc and VirtualAlloc family of functions.

The memory-allocation functions are mostly based around OS functionality, but the debug version exposes a fair bit of additional functionality.

The Win32 memory management functions include additional functionality, including data execution prevention, enclave, some older APIs (like local/global memory), and integration with file mapping.

Android

The most common allocator you'll find in Android today is jemalloc. It reduces contention by having per-CPU arenas - amongst a number of features of course.

The jemalloc project page contains lots of links and resources.

iOS

I couldn't get a "best" answer here honestly - I would like to be more educated on this if at all possible. Even browsing Apple's documentation, it seems there are multiple allocators in use for different subsystems, for example Core Foundation has a distinct API of its own. But what exactly underlies a vanilla 'malloc' request in terms of implementation and allocator design/lineage, I was uanble to find from public sources.

Michael Eisel has done some investigation of his own as well, and seems to have observed the multiple allocators himself (although some are clearly not "the" allocator - libsystem_malloc.dylib is the likely winner for general-purpose stuff). Unfortunately I don't have a handy setup right now to look into this more deeply.

Honorable Mentions

Happy memory allocations!

Tags:  androidcodingdesign

Home