Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to munmap() a mmap() file?

I have relatively new to C++ and I am learning from another guy's code. His code reads from a mmapped file, but does not free any mapped memory in the end. In my understanding, mmap() map files into virtual memory. Don't I need to release those mapped memory in some way, like, calling munmap()?

like image 398
Fenwick Avatar asked Oct 26 '14 02:10

Fenwick


People also ask

What is mmap () used for?

The mmap() function is used for mapping between a process address space and either files or devices. When a file is mapped to a process address space, the file can be accessed like an array in the program.

Does munmap free memory?

munmap(allocation, 5000); free(3) can only be used to free memory allocated via malloc(3) .

What library is mmap in?

mmap() and munmap() functions are provided by sys/mman. h library.


2 Answers

I believe you should release mapped memory with munmap. But it will be released automatically (like close syscall for regular files or sockets) after exit(). Remember, that implicit closing/unmapping is bad style!

like image 126
BHYCHIK Avatar answered Sep 17 '22 15:09

BHYCHIK


When you are done just use munmap() unless your program is exiting, then there is no need, it will unmap the segment(s) automatically at exit.

like image 27
codenheim Avatar answered Sep 20 '22 15:09

codenheim