1

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.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Aamir
  • 443
  • 3
  • 16

2 Answers2

1

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.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
0

I believe you are looking for:

a way to control how memory is being allocated on the stack, at least in the context of not overwriting already-used memory

Of course, that's taken care by the OS! The low level system calls will make sure that a newly created automatic variable will not be written upon an already used memory block.

In your example:

for (int i = 0; i < 5; i++) {
  int nums[5];
  ...
}

this is not the case, since nums will go out of scope, when the i-th iteration of the for loop terminates.

As a result, the memory block nums was stored into during the first iteration, will be marked as free when the second iteration initiates, which means that when nums of the first iteration is going to be allocated in the stack, it will not be aware of any existence of the nums of the first iteration, since that has gone already out of scope - it doesn't exist!

gsamaras
  • 71,951
  • 46
  • 188
  • 305