Reputation: 6354
How do you create a new malloc()
function defined in C language ?
I don't even have an elflike hint as to how to do this , how to map virtual space address with physical space , what algorithm to follow ? I do know that malloc() is not so efficient as it can cause fragmentation. So something efficient can be created. Even if not efficient , how to implement a naive C malloc function?
It was asked recently in an interview.
Upvotes: 3
Views: 3146
Reputation: 1361
I think it's a nice example of malloc in An example in Chapter 8.7 of C Programming Language book:
Upvotes: 3
Reputation: 150108
Wikipedia actually provides a good summary of various malloc implementations, including ones optimized for specific conditions, along with links to learn more about the implementation.
http://en.wikipedia.org/wiki/C_dynamic_memory_allocation
A general-purpose allocator. The GNU C library (glibc) uses an allocator based on dlmalloc.
In order to avoid lock contention, jemalloc uses separate "arenas" for each CPU. Experiments measuring number of allocations per second in multithreading application have shown that this makes it scale linearly with the number of threads, while for both phkmalloc and dlmalloc performance was inversely proportional to the number of threads.
Hoard uses mmap exclusively, but manages memory in chunks of 64 kilobytes called superblocks. Hoard's heap is logically divided into a single global heap and a number of per-processor heaps. In addition, there is a thread-local cache that can hold a limited number of superblocks. By allocating only from superblocks on the local per-thread or per-processor heap, and moving mostly-empty superblocks to the global heap so they can be reused by other processors, Hoard keeps fragmentation low while achieving near linear scalability with the number of threads.
Every thread has local storage for small allocations. For large allocations mmap or sbrk can be used. TCMalloc, a malloc developed by Google, has garbage-collection for local storage of dead threads. The TCMalloc is considered to be more than twice as fast as glibc's ptmalloc for multithreaded programs.
dmalloc (not covered by Wikipedia)
The debug memory allocation or dmalloc library has been designed as a drop in replacement for the system's malloc, realloc, calloc, free and other memory management routines while providing powerful debugging facilities configurable at runtime. These facilities include such things as memory-leak tracking, fence-post write detection, file/line number reporting, and general logging of statistics.
Upvotes: 7