Sometimes code that use heap allocation functions throw this error: munmap_chunk(): invalid pointer
It appears by context munmap_chunk()
is a function, and these errors are this function throwing them. What is this function and what does this function do?
My question is rather simple, so there is no reason to provide a lot of extra information: What is munmap_chunk()
?
Two simple functions malloc
and free
must solve contradicting problems:
To solve both, allocators (at least glibc, musl, windows) have a threshold for a size of an allocated object: allocations greater than that size are done by direct call to mmap
/VirtualAlloc
while freeing such chunks goes directly to munmap
/VirtualFree
.
This makes it possible to keep malloc
fast for small allocations, while keeping it memory-efficient for large ones (as it can free large chunks of memory immediately).
The threshold value is usually about 128 KB and larger (see DEFAULT_MMAP_THRESHOLD_MIN
in glibc, MMAP_THRESHOLD
in musl).
Function munmap_chunk
in glibc is responsible for that and is usually called like this:
if (chunk_is_mmapped(p)) {
munmap_chunk(p);
return;
}
You will see munmap_chunk(): invalid pointer
message when passing a pointer to a chunk of memory that looks like mmap
-allocated chunk, but upon investigation has invalid size, which means there is a memory corruption or free
misusage.
Aside from this, it is also responsible of keeping track of a number of allocated through mmap
chunks to workaround VMA merging issue on Linux kernel issues.