Search code examples
cstackalloca

Declaring memory on stack overwrites previously declared memory


How can I allocate memory on the stack and have it point to different memory addresses so I can use it later? For example. this code:

for (int i = 0; i < 5; i++) {
    int nums[5];
    nums[0] = 1;
    printf("%p\n", &nums[0]);
}

Will print out the same address every time. How can I write memory to stack (not the heap, no malloc) and have it not overwrite something else that's on the stack already.


Solution

  • You could use alloca to allocate a different array from the runtime stack for each iteration in the loop. The array contents will remain valid until you exit the function:

    #include <stdlib.h>
    #include <stdio.h>
    
    void function() {
    
        for (int i = 0; i < 5; i++) {
            int *nums = alloca(5 * sizeof(*nums));
            nums[0] = 1;
            printf("%p\n", (void *)nums);
            /* store the value of `num` so the array can be used elsewhere.
             * the arrays must only be used before `function` returns to its caller.
             */
            ...
        }
        /* no need to free the arrays */
    }
    

    Note however that alloca() is not part of the C Standard and might not be available on all architectures. There are further restrictions on how it can be used, see the documentation for your system.