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()?
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!
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
).
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.
© 2022 - 2024 — McMap. All rights reserved.