Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the two allocation methods?

Tags:

c

malloc

I want to test how much the OS does allocate when I request 24M memory.

    for (i = 0; i < 1024*1024; i++)
            ptr = (char *)malloc(24);

When I write like this I get RES is 32M from the top command.

    ptr = (char *)malloc(24*1024*1024);

But when I do a little change the RES is 244. What is the difference between them? Why is the result 244?

like image 447
Fei Xue Avatar asked Jul 27 '26 00:07

Fei Xue


1 Answers

The allocator has its own data structures about the bookkeeping that require memory as well. When you allocate in small chunks (the first case), the allocator has to keep a lot of additional data about where each chunk is allocated and how long it is. Moreover, you may get gaps of unused memory in between the chunks because malloc has a requirement to return a sufficiently aligned block, most usually on an 8-byte boundary.

In the second case, the allocator gives you just one contiguous block and does bookkeeping only for that block.

Always be careful with a large number of small allocations, as the bookkeeping memory overhead may even outweigh the amount of the data itself.

like image 156
Blagovest Buyukliev Avatar answered Jul 28 '26 14:07

Blagovest Buyukliev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!