Home > database >  C How to unmap unused global array from RAM?
C How to unmap unused global array from RAM?

Time:06-16

In C when you declare a big array, say 500MB, it doesn't get mapped to RAM immediately because it is not used yet. As soon as I access a page from the array for the first time, it gets mapped to physical memory. Now the system knows that I am using that page, but how do I tell the system that I am not using some page anymore and that it can unmap it at its will?

In my case I just need to occasionally, so not all the time, fill a big array and operate on it with fast random access. Now I could use malloc every time, but why would I do that? There are ways to tell the system that you don't need some page, but they all both unmap it from physical space and virtual space. I just want to unmap it from physical space. Is it not possible?

CodePudding user response:

You don't need to do anything special.

Memory management units automatically move virtual memory pages in and out of physical RAM as needed. If a page hasn't been used in a while, and its memory is needed for something else, it will be paged out. Physical RAM holds the pages that have been used most recently, older pages are just evicted if they're backed by a file (e.g. the text segment of programs), or they're written to the swap area of disk and then evicted.

When you're done with the entire array you should deallocate it with delete[]. Depending on the design of the memory allocator this may or may not remove the memory pages from your virtual memory, but you don't have any direct control over that.

If you're talking about a static array, there's no way to indicate that you're done with it. If you need to do that, the array must be allocated dynamically with new so you can delete it.

CodePudding user response:

After a lot of research, luckily, I found another post, where it is exposed that using mmap() with MAP_ANON|MAP_SHARED option to allocate the array and madvise() with MADV_REMOVE option does the trick. You can check the man-pages for details.

  • Related