I have implemented by own malloc and free using mmap. Now since unlike free, munmap also takes length as parameter, therefore I put length as an additional information in the mapped memory.
The code for my malloc and free is shown below. I want to ask, if this code is good or am I still missing anything or doing something in a wrong way.
void * malloc ( size_t size )
{
int *plen;
int len = size + sizeof( size ); // Add sizeof( size ) for holding length.
plen = mmap( 0, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0 );
*plen = len; // First 4 bytes contain length.
return (void*)(&plen[1]); // Memory that is after length variable.
}
void free ( void * ptr )
{
int *plen = (int*)ptr;
int len;
plen--; // Reach top of memory
len = *plen; // Read length
munmap( (void*)plen, len );
}
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.
For very large requests, malloc() uses the mmap() system call to find addressable memory space. This process helps reduce the negative effects of memory fragmentation when large blocks of memory are freed but locked by smaller, more recently allocated blocks lying between them and the end of the allocated space.
Typical implementations of malloc use brk / sbrk as the primary means of claiming memory from the OS. However, they also use mmap to get chunks for large allocations.
You can use mmap to allocate an area of private memory by setting MAP_ANONYMOUS in the flags parameter and setting the file descriptor fd to -1 . This is similar to allocating memory from the heap using malloc , except that the memory is page-aligned and in multiples of pages.
Some observations:
int
and size_t
have the same size. If you want to store a size_t
value at the head of the allocation, then why don't you just do that? Why introduce int
?mmap()
, and typically allocations cannot be smaller than a "page". Most real allocators try to avoid calling OS-level functionality on every malloc()
, in various ways.mmap()
fails, it will return MAP_FAILED
, and so should malloc()
. Thus, you need to test for that before de-referencing the pointer returned by mmap()
.free(NULL)
should be a valid thing to do; with your implementation it will very likely cause a crash since you don't NULL
-check the argument before assuming it's valid.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With