Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding mmap

I have been looking to get difference between malloc and mmap system call. What is the exact difference between these two? Which is recommended?

like image 609
username_4567 Avatar asked Jun 23 '26 00:06

username_4567


1 Answers

mmap() is a system-level address to map data from a file on disk. With mmap() you can refer to any file on disk as if it is a simple byte[] array. It may be used in any of following applications.

  • Whenever you request a data from a file on disk, it is loaded in RAM. If you have two separate programs requiring data from the same file, you can use mmap() to directly access that file from disk, thereby reducing otherwise redundant RAM usage.

  • When you are dealing with data so large that it can't be fit in main memory (RAM), you might use mmap() to access portion of the data of the file which is physically stored on your disk, thereby, again reducing RAM usage and handling larger than RAM data effectively.

Note that in a 64-bit system mmap() can address any location on disk but not in a 32-bit system! Because in a 32-bit system the maximum addressable space is limited to 2^32 - 1 (4GB) but on a 64-bit system petabytes of locations can be addressed.

malloc() gives you a pointer to some space from heap (in RAM) to store a temporary object.

The only similarity between mmap() and malloc() is that they both return pointers. But mmap() points to memory on disk and malloc() points to memory on heap.

like image 126
Sravan Avatar answered Jun 26 '26 10:06

Sravan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!