Do I have to munmap() a mmap() file?
Asked Answered
E

3

7

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()?

Enrich answered 26/10, 2014 at 2:26 Comment(0)
B
7

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!

Beefwitted answered 26/10, 2014 at 2:35 Comment(0)
P
4

munmap happens automatically on exit

So if the program is going to exit anyways, you don't really need to do it.

man munmap 4.15 says:

The munmap() system call deletes the mappings for the specified address range, and causes further references to addresses within the range to generate invalid memory references. The region is also automatically unmapped when the process is terminated. On the other hand, closing the file descriptor does not unmap the region.

If the program doesn't exit, of course, you leak memory, just as with malloc (which nowadays uses mmap).

Pepsinate answered 27/8, 2018 at 14:15 Comment(0)
D
2

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.

Diskin answered 26/10, 2014 at 2:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.