(GNU) C offers at least two mechanisms for manipulating variable data on stack - the first one is the alloca
function and its relatives (e.g. strdupa
), and the second is the "Variable Lenght Array" feature.
The problem with alloca
is that it doesn't seem to allocate continous regions in memory - the program
#include <alloca.h>
#include <stdio.h>
int main(void) {
int *a = alloca(sizeof(int));
int *b = alloca(sizeof(int));
printf("b-a = %ld (%ld)", b - a,
(char *)b - (char *)a);
return 0;
}
prints
b-a = -4 (-16)
which suggest that subsequent allocations possibly return quadruples of words (but I'd expect it to be implementation-specific - I tried this code only on my ARM-based phone).
Is there any "sanctioned" way of pushing single values on the stack, rather than allocating them with size that is known upfront?
I mean something like:
int x = 4;
push(x, sizeof(x))
int y = *(int *) pop(sizeof(x));
assert(x == y);
I'm looking for a solution that would work on both x86 and ARM. (I consider that studying ABIs of these platforms and writing macros that would expand to assembly that explicitly manipulates stack pointer would be an option, but I don't have time to explore this on my own)