alloca()
allocates memory on the stack rather than on the heap, as in the case of malloc()
. So, when I return from the routine the memory is freed.
Here's why:
char x;
char *y=malloc(1);
char *z=alloca(&x-y);
*z = 1;
Not that anyone would write this code, but the size argument you're passing to alloca
almost certainly comes from some sort of input, which could maliciously aim to get your program to alloca
something huge like that. After all, if the size isn't based on input or doesn't have the possibility to be large, why didn't you just declare a small, fixed-size local buffer?
Virtually all code using alloca
and/or C99 vlas has serious bugs which will lead to crashes (if you're lucky) or privilege compromise (if you're not so lucky).