Pusheen_the_dev
Pusheen_the_dev

Reputation: 2197

How to use munmap custom malloc

I'm trying to recode malloc and free functions but i got a problem with munmap..

With my custom malloc, I create a pool of memory with mmap (Ex : 4Kb), so I can return an index of this pool as an address when my malloc is called.

This work fine, but when I use my custom free (Call to munmap) then I want to allocate something else with my custom malloc, I got a segfault, like if my ENTIRE pool was disallocated by munmap..

Example:

Ask 1024 bytes to my malloc
-> First call so malloc allocate a pool of 4 * pagesize() (So 16 000     
bytes)
-> Return to me an addr than I use. (addr[0] = 42)
-> Free with munmap this address (munmap(addr, 1024))
-> re ask to my malloc 1024 bytes
-> Try to fill it with something and segfault.

I don't really understand what is happening. Does munmap delete all my pool ?

Sorry for the poor english..

Upvotes: 1

Views: 770

Answers (1)

mtijanic
mtijanic

Reputation: 2902

You are unmapping the entire page.

The address addr must be a multiple of the page size. All pages containing a part of the indicated range are unmapped, and subsequent references to these pages will generate SIGSEGV. It is not an error if the indicated range does not contain any mapped pages.

munmap(2)

So when you munmap your first allocation, you unmapped the entire first page. You should wait to unmap only when the entire page is deallocated.. Or just not unmap at all - Just be sure two processes don't get memory from the same page, so there are no security vulnerabilities.

Upvotes: 3

Related Questions