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:

https://groups.google.com/forum/#!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:

http://en.wikipedia.org/wiki/Mmap#File-backed_and_anonymous

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;
ptr = mmap(0,4096,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED,-1,0);
if(ptr == MAP_FAILED)
{
perror("Error in mapping\n");
exit(1);
}
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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s