Diwakar Sharma
Diwakar Sharma

Reputation: 425

malloc : Anonymous mapping and magic area

I was just fiddling around memory mappings and wanted to view user space virtual memory region mappings. Wrote some lines like

char *ptr = NULL;
printf("Allocating 300KB\n");
ptr = malloc (300*1024);    
printf("Allocated at %p.. sleeping\n", ptr);
sleep (30);
free (ptr);
printf("Freed... sleeping\n");
sleep (30);    

On running the program, pmap on the pid shows allocated region as:

00007f73b1e57000    316K rw---    [ anon ]

while program o/p says:

Allocated at 0x7f73b1e57010.. sleeping

Is this 16KB extra allocation for what we call magic region on allocation? In the kernel, the corresponding vm_area_struct will hold ranges visible to program or the entire range from starting of magic region?

Upvotes: 2

Views: 1315

Answers (2)

cmidi
cmidi

Reputation: 2010

To start with any OS which has a Memory management unit manages all it's memory (heap, code space, stacks I/O memory) using the MMU, all memory exists in a virtual space and page tables are used to translate the virtual addresses into physical addresses, the mapping to physical memory is dependent on the OS

malloc will return a pointer to heap memory using sbrk call which in turn will increase the heap size, the MMU when this memory is accessed will then allocates actual physical page and maps to the virtual address.

According to pmap manual page the output shows and not the allocated memory block size from malloc but the virtual mapping size.

 "Virtual Mapping Size (Kbytes)

     The virtual size in kilobytes of each mapping."

For a quick experiment to check if the block size of the memory returned from malloc should be equal to the output from pmap.

To prove the point I did a quick test using this code

 int main(int argc, char **argv)
 {
      char *timeBuf = (char *)malloc(100);
      printf("allocated address is %p\n",timeBuf);
      int i;
      for(i =0 ;i < atoi(argv[1]);i++)
      {              
      }
      return 0;
}

the pmap output is:

`0000000001338000    132K rw---    [ anon ]`

The returned pointer from malloc:

allocated address is 0x1338010

I think the 16 bytes is kept by malloc for book keeping in it's headers as mentioned in previous answers. As you can se the allocated memory in program is just 100 bytes but the pmap virtual memory size is 132K

So to answer your question in short no this is not related to the magic area.

Upvotes: 1

Mike Nakis
Mike Nakis

Reputation: 62064

The difference is not 16KB, it is 16 bytes. Which most probably corresponds to the header that malloc has to allocate before your memory block so as to link blocks together, etc.

Upvotes: 2

Related Questions