mmap v/s malloc

I was browsing LKNB forum and came across a code snippet doing mmap() with MAP_ANONYMOUS flag. The surprise with this mmap() call was the “fd” used in this call. It was -1. Doing a quick read of man pages did not help much. Though it showed that fd argument is ignored if the MAP_ANONYMOUS flag is used.

As usual, I did google and came across this nice link which explains the benefits of using mmap() in special situations:!topic/comp.sys.hp.hpux/TNR-GpVK73k

Wiki page of mmap also has some information on anonymous (and file backed) mapping. Here is the link:

Having said all this, following is the code snippet which triggered all the confusion. The beauty of the code is, it tries to map the NULL address to a valid memory location :-)

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

int main(void)
int *ptr = NULL;
if(ptr == MAP_FAILED)
perror("Error in mapping\n");
printf("After mmap\n");
*ptr = 16;
printf("Contents of address 0x%x is :: %d\n",ptr,*ptr);
return 0;

To make above code work, /proc/sys/vm/mmap_min_addr needs to be set to 0.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s