Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does munmap needs a length as parameter?

Tags:

linux

kernel

mmap

I was wondering, why should the size of mapped memory being one parameter passed in, since there couldn't more more than one mapping starting from same address (could they ?), why won't linux kernel record both start address, length together, but let userspace program remember them.

I mean, why wouldn't it be, just use the start address as primary key to store the information tree.

like image 924
daisy Avatar asked Aug 22 '12 15:08

daisy


1 Answers

You can munmap a subrange of memory addresses that you have previously mapped. For example:

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

int main()
{
    int pagesize = sysconf(_SC_PAGESIZE);
    char *addr = mmap(NULL, 4 * pagesize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    addr[pagesize] = 'X';
    munmap(addr, pagesize);

    printf("%c\n", addr[pagesize]);
}
like image 174
user1202136 Avatar answered Oct 05 '22 12:10

user1202136