by secretsatan · 4y ago · 0 comments
When you deallocate small amounts of memory, the underlying C library allocator will keep the deallocated memory around and not return it to the OS in case you need a similar sized piece of memory soon.
It is very rare for memory ever to be freed to the OS before process exit. Malloc never does.
And, zeroing the memory, if code later uses it like a pointer, that will be null and the use will trap.
[1]: <https://github.com/bminor/glibc/blob/a364a3a7090b82ddd30e920...>
Unmapping trashes page-map caches of other threads in the process. That involves inter-core interrupts. Not pretty.
Most CPUs provide memory permissions with granularity of pages, which are usually 4 KB in size. The OS manages these by modifying a "page table" which the CPU uses. Changing the page table is not free, so the userland allocator (malloc/free) will request large blocks of memory from the OS (with mmap) (or sbrk, if you're a dinosaur) and then divide them up into smaller blocks for your program. They typically remain accessible until the entire original block is freed.
If you allocate a large enough block of memory, it will typically just be backed by one region of pages made with mmap. Then, when you free it, the allocator will munmap it. You can test this out by allocating a large block of memory, freeing it, and then dereferencing it.
Your system might do this for 1 MiB allocations, for example... change the allocation size and see whether it still crashes.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
volatile int *ptr = malloc(1024 * 1024);
puts("*ptr = 1");
*ptr = 1;
free(ptr);
puts("*ptr = 2");
*ptr = 2;
}They're 64KB on RHEL/CentOS 8 on 64-bit ARM, see for instance https://git.centos.org/rpms/kernel/blob/c8/f/SOURCES/kernel-... which is AFAIK the kernel configuration for CentOS 8 (search for CONFIG_ARM64_64K_PAGES=y).
Some of the more common malloc implementations out there are dlmalloc, jemalloc, and tcmalloc. Here is where they call munmap.
https://github.com/ennorehling/dlmalloc/blob/71296436f979a35...
https://github.com/jemalloc/jemalloc/blob/c0c9783ec9289e6d1d...
Note that not all allocators work this way, you can see that tcmalloc will instead MADV_DONTNEED. (You can find munmap in tcmalloc, but it's not being used to free memory.)
https://github.com/google/tcmalloc/blob/48808681a9f38e974b49...
Some CRT's just go get their own block of memory then malloc out of that. Some use the OS extensively to minimize that sort of thing. It just depends.