2

Currently working on a code I realized that it used to call malloc multiple times (around 10 million calls) and allocated small chunks (around 10 bytes) every time.

I changed the code a little and instead of calling malloc 10 million times I now call malloc 10 times allocating a large chunk of memory (10 million bytes) every time.

With this change I noticed that peak memory consumption of my code changed from ~15 GB to ~14 GB.

Why is this happening? Does malloc allocates some extra chunk with every call?

melpomene
  • 84,125
  • 8
  • 85
  • 148
nav_jan
  • 2,473
  • 4
  • 24
  • 42

1 Answers1

7

definitely. Because malloc() allocates some amount of bytes for meta-data. so if multiple malloc() leads to more meta-data.

This link gives you more detail about how malloc allocates memory as well as metadata.

Jeyaram
  • 9,158
  • 7
  • 41
  • 63
  • Yes... but allocating a big block and parcelling it yourself most likely doesn't really change that, because then *you* need to apply that metadata... Rule #1 of optimizing applies: Measure, optimize, measure. – DevSolar Dec 04 '12 at 11:51
  • @DevSolar: well, clearly not as much: the OP measured it already. – ams Dec 04 '12 at 11:55
  • @ams: Granted. But it's dangerous to take an extreme example (like the OP's 10 million calls) and abstract them into hard and fast rules ("always do your own memory management, it's faster and saves memory"). >10 years of maintenance coding have taught me how bad such hard & fast thinking can go in the long run. ;-) – DevSolar Dec 04 '12 at 15:26