I'm trying to figure out how alloca() actually works on a memory level. From the linux man page:
The alloca() function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca() returns to its caller.
Does this mean alloca() will forward the stack pointer by n bytes? Or where exactly is the newly created memory allocated?
And isn't this exactly the same as variable length arrays?
I know the implementation details are probably left to the OS and stuff. But I want to know how in general this is accomplished.
Yes,
allocais functionally equivalent to a local variable length array, i.e. this:and this:
both allocate space for
nelements of typeinton the stack. The only differences betweenarrin each case is that 1) one is an actual array and the other is a pointer to the first element of an array, and 2) the array's lifetime ends with its enclosing scope, while theallocamemory's lifetime ends when the function returns. In both cases the array resides on the stack.As an example, given the following code:
When I run this I get:
Which shows that the the memory returned from
allocasits between the memory for the two VLAs.VLAs first appeared in the C standard in C99, but
allocawas around well before that. The Linux man page states:BSD 3 dates back to the late 70's, so
allocawas an early nonstandardized attempt at VLAs before they were added to the standard.Today, unless you're using a compiler that doesn't support VLAs (such as MSVC), there's really no reason to use this function since VLAs are now a standardized way to get the same functionality.