Phil CK

Allocation in C

Last updated on

C is all about manual everything, and you will have to allocate some memory at some point.

/* alloc.c */

#include <stdio.h>
#include <stdlib.h>
#include <alloca.h>


int
main() {
        /* malloc's a single int */
        int *foo = malloc(sizeof(*foo));

        /* malloc's an array of 10 ints */
        int *bar = malloc(sizeof(bar[0]) * 10);

        /* realloc changes the size of the memory but keeps
           the contents intact */
        bar = realloc(sizeof(bar[0]) * 100);

        /* calloc works the same but it will initalize the memory to zero.
           calloc takes an paramater at the start to specify how
           many instances of boo - in this case 1 */
        int *boo = calloc(1, sizeof(*boo), 1);

        /* alloca allocates memory on the stack, this can be fast
           but can lead to nasty things like stack overflow */
        int *baz = alloca(sizeof(*baz));

        /* free the memory */
        /* we dont free `baz` because it is on the stack, it will free
           itself after it passes the next `}` */
        free(boo);
        free(bar);
        free(foo);

        return 0;
}

Compile and run,

gcc alloc.c && ./a.out

this outputs nothing.

Managing memory in C can seem complicated, and some domains like games/realtime will rely on allocators to allocate large chunks of memory and free them at the same time. Most platforms also allow allocating virtual memory which can be quite fun.