harish Dubakula
harish Dubakula

Reputation: 128

Clearing Memory in RAM?

I have some code in c++ which is used to allocate memory and frees it, though RAM is not clearing immediately...My doubts are (I am using linux OS)

1)is Operating System takes time to deallocate memory which is freed?

2)How we can force the RAM to clear the freed memory in time intervals?

Thank you

Upvotes: 1

Views: 1171

Answers (1)

Michael Veksler
Michael Veksler

Reputation: 8475

The subject of freeing memory is more complicated than you would expect. There are whole articles devoted to allocation and deallocation policies.

Usually, big blocks are allocated with mmap (memory mapped file), which is immediately released with free. Small chunks of memory are carved out of a big chunk of heap, the size of which is managed with sbrk family of functions.

Freeing memory carved out of the big heap is usually done by putting the freed chunk into a free list (or similar). The free list is managed by the C library, and is not freed by the kernel through sbrk. The process keeps the freed chunk indefinitely.

Sometimes, a contiguous area of memory, at the end of the heap, is in the free list. In that case, the C library might decide to shrink the heap, and return the memory to the operating systems. This is a rare occasions, since it is enough to have a small chunk of memory at the end of the heap to prevent that from happening.

Check mallopt for Linux to find out how to control the aggressiveness of free release policy. Note that this call is not portable and changes from one operating system to another. Also, malloc_trim(0) is a non-portable, Linux-only, way to force the C library to return all memory it can, back to the OS. Most likely, your Operating System has a similar non-portable call for the same ends.

Usually, small and medium chunks of memory are never returned to the Operating System, and are kept in the internal free list for the lifetime of the process. Next calls to malloc will usually allocate memory from this free list.

The only way to force memory to be freed is to manage it directly, avoiding malloc/free altogether. You can allocate a big chunk of memory through mmap, and then unmap it when you are done. With stock malloc/free it is very difficult to make sure the allocation (and free) are done in LIFO (last in first out), otherwise there will be small block of memory that interfere with releasing memory to the OS.

note

The details differ between operating systems. Windows and POSIX systems have different policies and different memory mapping primitives. On OSs without virtual memory, like DOS, all memory could be returned immediately to the OS (no mmap, nor sbrk).

Upvotes: 3

Related Questions