Reflections on Allocations

In C, allocations come in two forms. By using some amount of your thread's stack, or by using a heap allocator such as malloc() and free(). Sometimes it is hard to know which to use, so I'd like to set out some guidelines to help you make the right choice.

First, lets compare what stack and heap allocations do.

Stack allocations are very cheap and fast. In fact, their only cost is incrementing the number of bytes in our stack frame, which will automatically be unwinded upon returning from the function. If you perform a sufficially large allocation, you could end up going past the end of your stack space, so functions like alloca() are generally discouraged. However, they can be very useful when working with a safe amount of data.

Heap allocations require a lot overhead to manage. Every time you use them various information needs to be stored. They are prone to fragmentation over time since lots of small allocations can make it difficult to find enough contiguous space for larger allocations.

Do use heap allocations when

Do use stack allocations when

Additionally, you might be asking yourself, should I use gslicenew or gmalloc? Note that gslice_* is a SLAB style allocator within GLib and provides automatic memory caching based on structure size. It helps speed up allocations in most cases (however, I'd like to see some comparisons against tcmalloc).

Do use gslicenew or variants when

Do use gnew, gmalloc or variants when

If you have any corrections or suggestions please let me know and I will update accordingly.

-- Christian Hergert 2013-07-11

Back to Index