I recently saw the following post:
A memory allocator isn\'t lower level than malloc. (The default allocator typically calls malloc directly or indi
Alright, I am not sure about Linux, but when it comes to windows...
Memory can be allocated in two categorized places.
1) Heaps (Process Heap, Custom Created Heaps) see -> http://msdn.microsoft.com/en-us/library/windows/desktop/aa366711(v=vs.85).aspx using functions like HeapAlloc & HeapFree. LocalAlloc and LocalFree can be used as 'shortcuts' to HeapAlloc when you want to allocate in the default process heap.
2) Virtual Memory (usually only process-specific due to access restrictions in global virtual memory for security), using VirtualAlloc, VirtualFree. see -> http://msdn.microsoft.com/en-us/library/windows/desktop/aa366916(v=vs.85).aspx
To my knowledge, malloc will use the heap allocation functions on windows.
I hope this helps.
malloc() and friends are considered part of the runtime system that comes with a compiler. So each compiler can and does use different OS calls to implement malloc.
As others have said, on Linux the options are sbrk() and mmap().
On Windows the options are HeapAlloc() and VirtualAlloc().
On Windows, malloc
implementations will usally call the win32 heap functions like HeapCreate
, HeapDestroy
, HeapAlloc
, HeapFree
. Those functions will call the NTDLL usermode heap manager located within ntdll.dll, those functions will have the RtlxxxHeap
name, RtlAllocateHeap
, RtlCreateHeap
, etc...
In the end system calls within the NtxxxVirtualMemory
group will be called, NtAllocateVirtualMemory
, NtQueryVirtualMemory
, NtFreeVirtualMemory
.
In Windows, in recent versions of MSVC, malloc (and C++ new
, as it is implemented using the same fundamentals for the actual memory allocation part of new
) calls HeapAlloc(). In other versions, such as g++ mingw, the C runtime is an older version, which doesn't call quite as directly to HeapAlloc
, but at the base of it, it still goes to HeapAlloc
- to find something different, we need to go back to Windows pre-95, which did have a GlobalAlloc
and LocalAlloc
set of functions - but I don't think people use 16-bit compilers these days - at least not for Windows programming.
In Linux, if you are using glibc
, it depends on the size of the allocation whether it calls sbrk or mmap - mmap
(with MAP_ANONYMOUS
in the flags) is used for larger allocations (over a threshold, which I believe is 2MB in the typical implementation)
My question is- how is malloc implemented in the following Operating systems?
On Linux there are two famous malloc
implementations:
dlmalloc (Doug Lea's malloc)
ptmalloc
On Linux libc like glibc, eglibc or newlib implement ptmalloc or a variant of ptmalloc.
what are the OS-specific functions which are called/implementations of malloc()?
On Unix and Linux systems sbrk
and mmap
system calls are used. See man 2 sbrk
and man 2 mmap
for more information.