Search

A technology, a device or an article

Why old bytes can remain in RAM after MADV_FREE

MADV_FREE lets the kernel discard old page contents. Retained bytes, new writes and RSS describe different aspects of lazy freeing.

Green linocut of a hand releasing leaves over empty rectangular outlines
ITNWS AI-generated conceptual illustration. Released leaves evoke permission to forget previous memory contents.ITNWS · image_gen · Original ITNWS AI-generated conceptual editorial illustration

“The allocator returned free pages to the system via MADV_FREE. I then read the area and saw the old byte pattern. Does this mean the release didn’t work?” This is a hypothetical letter written by the editorial team, and not a message from a fictitious developer. The question is useful because it forces you to distinguish between two things: allowing the kernel to forget the contents and the moment when it actually uses this permission. For MADV_FREE, time may pass between them. The presence of old bytes in one observation does not give the program the right to continue to rely on them.

Let’s start with what the program owns here. It still has a virtual mapping: addresses do not disappear just because of a successful madvise. What changes is the contract for the previous contents of certain pages. The application indicates that it is no longer needed, so the kernel is free to release the associated physical storage without preserving those values. This is not the usual moving of live data to swap for the sake of future recovery. For pages whose old contents may be discarded, it is no longer necessary to save old data. It is the abandonment of this responsibility that makes lazy freeing useful.

Linux madvise manual, reviewed October 30, 2026, describes MADV_FREE for private anonymous pages. A suitable area is a private anonymous mapping, such as an allocator workspace memory. It is not possible to automatically transfer the same contract to an arbitrary mapped file or shared mapping. The mapping type is set before the result is explained. The same address and size in two programs does not mean that the kernel received the same task regarding the origin and storage of bytes.

The answer to the letter therefore sounds somewhat unusual: it is acceptable to see the old pattern, but it is no longer possible to use it as the promised data. Freeing may be delayed until memory pressure occurs. As long as the page remains accessible in its original form, reading can return the old values. The kernel has the right to remove them later; accessing an already freed page will receive memory filled with zeros on demand. The "contents are now invalid" application event does not need to exist between reads. Permission was given earlier, by the successful call itself.

At this point a natural objection arises: is it possible to check one byte and understand whether the entire buffer is preserved? No, such verification does not create a preservation guarantee. Even the coincidence of all verified values only applies to the observation performed. Other pages in the area may be in a different state, and after monitoring, the ability to release the remaining ones will change. If the allocator is going to give the block back to the application, correctness must rely on the newly initialized contents and its own initialization rules. A successfully read old header is no substitute for such preparation.

Writing changes that situation. For a page marked MADV_FREE that has not yet been freed, a subsequent write will cancel the pending lazy freeing of that page. If the page has already been freed, a new write establishes current contents in the existing mapping. The kernel may not then discard the newly written data based on the previous permission. Therefore, the operation allows you to relatively cheaply return to use pages whose physical storage has not yet been reclaimed. But this return is due to writing, not reading, which revealed a pleasant coincidence of old values.

In this case, the kernel unit is a page, and the allocator unit can be much smaller. Let’s imagine hypothetical pages of 4096 bytes and an application block of 80 bytes in length. These are given example dimensions, not a universal property of any Linux machine. If there are active objects nearby on the same page, the entire page cannot be declared unnecessary for the sake of one freed block. The kernel does not know which parts of the page are occupied by living objects. The allocator must collect a free page or range of suitable pages, keeping its own metadata outside the passed area.

The madvise arguments follow the same page boundaries: the start address must be page-aligned and the size rounded accordingly. Trying to pass a convenient internal pointer requires understanding the actual scope. Failure of an operation and successful permission to discard contents have completely different consequences. Therefore, the return value belongs to the allocator logic and not to optional diagnostics. If the call fails, the program is not entitled to assert that the release has been achieved simply because the corresponding line is present in the source code.

Hands lift and stitch square patches in a grey and mustard textile
ITNWS AI-generated conceptual illustration. Removable patches evoke discardable pages and new contents, not a DRAM schematic. — ITNWS · image_gen · Original ITNWS AI-generated conceptual editorial illustration

Another question in the letter might be: “Then why does MADV_DONTNEED behave differently?” For normal private anonymous mapping, a successful MADV_DONTNEED changes subsequent accesses to zero-fill-on-demand. This is a more direct change to the visible content than allowing lazy abandonment of it. But even here mapping is preserved. The address does not become inaccessible, as after removing the mapping. It is necessary to compare the same type of memory: for mapped files and shared areas, different rules apply for restoring content from the corresponding source.

The mmap manual helps keep this distinction. The mapping defines the available virtual range, rights, and connection to the source. Physical residency and the preservation of individual values are related but distinct issues. Removing mapping via munmap terminates the corresponding basis for access to addresses. MADV_FREE does not have this general result. Therefore, the expression “returned memory” without qualification easily confuses the freed block inside the allocator, the kernel’s right to discard the page, and the complete removal of the virtual range from the address space.

The allocator has the right to keep free blocks for future allocations. When an application calls free, these blocks do not have to immediately disappear from its RSS. Internal lists and policies for coalescing ranges determine when a system call is possible. Then MADV_FREE adds another delay – this time on the kernel side. An outside observer sees the outcome of several decisions. It cannot determine from a single process metric how much of the hold is due to live objects, internal fragmentation, stored free arenas, or pages that have already been allowed to be abandoned.

proc_pid_smaps is useful for monitoring. Its LazyFree field reports the volume of pages marked accordingly; it is not the number of free objects managed by a language runtime, nor is it a promise to instantly return the entire number to other processes. The content of the report changes along with the operation of the application and reclaim. Linux proc documentation explains the meaning of mapping and memory accounting. Reading such data is useful as an observation of a specific moment, maintaining boundaries between the user allocator and the pages managed by the kernel.

RSS can remain substantial after lazy discard. This in itself does not prove a leak: the resources are still mapped and may be in memory, although the old contentss no longer need to be retained. The reverse statement would also be too strong. The presence of LazyFree does not explain the entire growth of the process and does not certify the absence of actual memory leaks. To investigate, it is necessary to compare changes in mappings, the needs of the application and the history of the allocator. A single release mark is no substitute for knowing which objects continue to hold references.

Don’t set up a check that requires you to save the rejected content and then call the resulting zeros RAM corruption. The application itself permitted these zeros in the appropriate context of future calls. A hardware memory error is another claim that requires other evidence. A useful allocator test would check that newly issued objects receive exactly the promised initialization, regardless of whether the kernel has time to reclaim or not. This requirement does not rely on a successful reading moment and remains correct under different system loads.

Comparison with POSIX adds another caution. posix_madvise documentation separates portable hints from Linux-specific semantic changes. Similar names DONTNEED do not make interfaces interchangeable in terms of visible results. A portable allocator typically selects an OS-specific implementation and supported API. If an abstraction promises to discard or preserve bytes, the implementation must honor that promise. Similarity between the names of a function and a constant is not enough to prove the same behavior on different systems.

There is also a historical caveat. The manual dates the appearance of MADV_FREE to Linux 4.5 and specifically notes the behavior before Linux 4.12 on systems without swap: pages could be freed immediately regardless of pressure. These versions are not described as today’s news. The qualification matters for honest reading of old reports and tests. The same program on a different kernel version could see a different moment when old data disappeared without violating the behavior documented for that environment. The history of an interface cannot be replaced by the assumption that any old example must be reproduced byte-by-byte today.

Side by side in Linux there are the MADV_COLD and MADV_PAGEOUT advice values, designed to treat data differently. The first makes pages more likely candidates for reclaim, the second tries to free memory through the usual methods of saving the desired content, including swapping anonymous data or writing modified file content. Their meaning is not to allow you to lose the only current copy of the bytes needed by the application. Therefore, the choice between these mechanisms begins with the question of whether the previous values are needed in the future. The desire to reduce resident volume does not in itself answer it.

Another important boundary for the allocator is also between the contents of an object and the allocator metadata. If the list of free blocks is stored directly in those pages that are to be declared unnecessary, a subsequent reclaim may destroy the list itself. The implementation must either keep the required metadata elsewhere or have a way to recover it without relying on discarded bytes. This is already an allocator design, and not a special madvise guarantee. It is these details that explain why the presence of a system interface does not make it safe to add it after each user free without revising the storage of internal information.

Thread ownership is another part of the contract. The mere fact that one thread has declared pages unnecessary does not give it the right to destroy data that another is still using. Ownership synchronization is on the application and allocator side. The system call manipulates pages rather than correcting the lost connection between the object’s lifecycle and the reader. Therefore, the call is made after a truly free range has been established. A lazy implementation can temporarily hide the ownership error: the old bytes are still available, and the incorrect code appears to work until the moment when reclaim uses the permission already given.

Additionally, MADV_FREE is not guaranteed to erase secrets. Delayed retention of former bytes is directly inconsistent with the promise to immediately remove their visible contents. Otherwise, the result would be the opposite of the original letter: the program wanted destruction, but was content with allowing future loss. Erasure, dump exclusion, and residency management require their own mechanisms and checks of scope. A specific conclusion is sufficient here: the mechanism for saving physical memory cannot be assessed as a procedure for the confirmed removal of sensitive data, when it deliberately allows for some time to read the previous values.

The reply to the hypothetical allocator author therefore ends with the contract offered to its user. The free range no longer needs its former contents; the kernel has permission to forget them. On the next allocation, the allocator supplies the values and access validity promised to the application, rather than asking it to guess which pages survived the pause. Both the old byte pattern and zeros after reclaim are then permissible internal circumstances. RAM serves the new work correctly because the required contents have been initialized again, rather than because a read happened to recover old bytes.

Sources & documentation

  1. Linux madvise manual ↗
  2. Linux mmap manual ↗
  3. POSIX madvise interface documentation ↗
  4. Linux proc PID smaps manual ↗
  5. Linux proc filesystem documentation ↗