Page 2 of 2

Re:using stack...

Posted: Wed Mar 24, 2004 3:41 pm
by mystran
Actually, alloca() is not just a stack probe. It's a memory allocator function, which basicly acts like malloc(), but allocates from stack, so that the memory allocated with alloca() is automatically deallocated when the stack frame (function) returns.

Basicly, it might be useful when it's necessary to allocate some dynamic amount of memory (say a varying length buffer) but malloc() can't be used -- say, not implemented, or there's possibility of a longjmp() without ever calling free().

From linux alloca man-page:
CONFORMING TO
There is evidence that the alloca function appeared in 32v, pwb, pwb.2,
3bsd, and 4bsd. There is a man page for it in BSD 4.3. Linux uses the
GNU version. This function is not in POSIX or SUSv3.
Gcc normally implements alloca() with inlined code, unless you use -fno-builtin, so it can be faster than using malloc() as it's basicly just a question of adjusting the stack-pointer and making sure rest of the code doesn't go mad. Cygwin uses alloca() as a kludge-fix on Windows, but the function itself is not Windows-specific.

Re:using stack...

Posted: Thu Mar 25, 2004 3:02 am
by Pype.Clicker
Candy wrote: [Ok, aside from the stack probing. What do you do with big things on the edge of memory? Or, with a function that has a split base ?
The first thing is to detect that an allocation occured. Problems may arise with any segmentation-based protection if one increases the stack pointer without making sure the whole chunk remains within the segment because stack faults occurs when you *reference* beyond the limit, not when you increase the pointer.
It could of course also be possible to expose the current 'stack chunk' limits to the user program so that it can check by itself if an alloca() can fit or not...

Once we detected more stack is needed and discovered that the current chunk is too small, we have two options:
  • expand the stack by chaining a new chunk to the current one
  • replace the current chunk with a larger one.
Note that in any of the two cases, as there may exists pointers towards stuffs on the current chunk, that chunk *must* remain in place and may not be discarded, so if you thought a 64KB chunk would be a sufficient extension to the current stack and that the same function performs a 256KB alloca() a bit later, you must remap the whole 64K chunk within the +256K chunk, "wasting" 64K of virtual memory ...