1.7. STACK
Local variable storage
A function could allocate space in the stack for its local variables just by decreasing thestack pointer
towards the stack bottom.
Hence, it’s very fast, no matter how many local variables are defined. It is also not a requirement to store
local variables in the stack. You could store local variables wherever you like, but traditionally this is how
it’s done.
x86: alloca() function
It is worth noting thealloca()function^63. This function works likemalloc(), but allocates memory
directly on the stack. The allocated memory chunk does not have to be freed via afree()function call,
since the function epilogue (1.6 on page 29) returnsESPback to its initial state and the allocated memory
is justdropped. It is worth noting howalloca()is implemented. In simple terms, this function just shifts
ESPdownwards toward the stack bottom by the number of bytes you need and setsESPas a pointer to
theallocatedblock.
Let’s try:
#ifdef __GNUC__
#include <alloca.h> // GCC
#else
#include <malloc.h> // MSVC
#endif
#include <stdio.h>
void f()
{
char *buf=(char*)alloca (600);
#ifdef __GNUC__
snprintf (buf, 600, "hi! %d, %d, %d\n", 1, 2, 3); // GCC
#else
_snprintf (buf, 600, "hi! %d, %d, %d\n", 1, 2, 3); // MSVC
#endif
puts (buf);
};
_snprintf()function works just likeprintf(), but instead of dumping the result intostdout(e.g., to
terminal or console), it writes it to thebufbuffer. Functionputs()copies the contents ofbuftostdout.
Of course, these two function calls might be replaced by oneprintf()call, but we have to illustrate small
buffer usage.
MSVC
Let’s compile (MSVC 2010):
Listing 1.38: MSVC 2010
...
mov eax, 600 ; 00000258H
call __alloca_probe_16
mov esi, esp
push 3
push 2
push 1
push OFFSET $SG2672
push 600 ; 00000258H
push esi
call __snprintf
(^63) In MSVC, the function implementation can be found inalloca16.asmandchkstk.asmin
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\crt\src\intel