Search code examples
cmemorymemory-managementmallocrealloc

Resizing string arrays that may be too big


Some background: I'm writing a C function that reads text from a file into a dynamically reallocated array. I start off with BUF_SIZE character, read until I've hit the limit, then reallocate. When I'm finished, I append \0 at the end of the text (not the end of the array).

Is it considered better to leave the array too big (and lose a little bit of memory -- very little) or realloc() to the smaller size?


Solution

  • Don't bother realloc()ing to the final size. When the memory is not needed anymore, you will free() it anyway, and unless the string is huge, chances are that even if you realloc() it to a smaller size, the alignment requirements of malloc() will not change the space actually reserved, so you just make a superfluous call to a quite expensive function.

    TL;DR: don't shrink the array!

    And a piece of good advice: statistically, it's worth doubling the allocation size each time you hit the previous limit.