I found that malloc()
allocates more memory spaces than I ask for.
struct { void *ptr; int var; } msg; // 16 bytes (checked by sizeof())
for (int i = 0; i < 100000000; i++)
malloc(sizeof(msg));
As the aforementioned code, malloc()
actually allocate 32 bytes per function call (calculated by top
), but valgrind
shows only 16 bytes per call indeed.
Why does malloc allocate more memory spaces than I ask for, and how to force malloc()
not to waste that much memory spaces?
Surprisingly, it allocates 32 bytes also even if the struct is 24 bytes, so I guess that the memory spaces are wasted. I am not sure whether malloc()
should allocate a multiple of 32 bytes. If it's true, than the memory spaces are wasted.
EDITED:
I've tested for other circumstances.
+---------+---------------------------+
| n | memory usage of malloc(n) |
+---------+---------------------------+
| 1 ~ 24 | 32 bytes |
+---------+---------------------------+
| 25 ~ 40 | 48 bytes |
+---------+---------------------------+
| 41 ~ 56 | 64 bytes |
+---------+---------------------------+
The memory is not fully used if n
is not 16 * m + 8
, m
∈ ℕ. Some memory spaces wasted are understandable because of memory alignment when n
equals 22, but it still should be regarded as wasted when n
equals 16. On most of the platforms, the size of minimum memory access unit is 4 bytes or 8 bytes, so why does GCC implementation choose 16 bytes per increase.