Why does alloca
not check if it can allocate memory?
From man 3 alloca
:
If the allocation causes stack overflow, program behavior is undefined. … There is no error indication if the stack frame cannot be extended.
Why alloca
does not / can not check if it can allocate more memory?
The way I understand it alloca
allocates memory on stack while (s)brk
allocates memory on the heap. From https://en.wikipedia.org/wiki/Data_segment#Heap :
The heap area is managed by malloc, calloc, realloc, and free, which may use the brk and sbrk system calls to adjust its size
From man 3 alloca
:
The alloca() function allocates size bytes of space in the stack frame of the caller.
And the stack and heap are growing in the converging directions, as shown in this Wikipedia graph:
(The above image is from Wikimedia Commons by Dougct released under CC BY-SA 3.0)
Now both alloca
and (s)brk
return a pointer to the beginning of the newly allocated memory, which implies they must both know where does the stack / heap end at the current moment. Indeed, from man 2 sbrk
:
Calling sbrk() with an increment of 0 can be used to find the current location of the program break.
So, they way I understand it, checking if alloca
can allocate the required memory essentially boils down to checking if there is enough space between the current end of the stack and the current end of the heap. If allocating the required memory on the stack would make the stack reach the heap, then allocation fails; otherwise, it succeeds.
So, why can't such a code be used to check if alloca
can allocate memory?
void *safe_alloca(size_t size)
{
if(alloca(0) - sbrk(0) < size) {
errno = ENOMEM;
return (void *)-1;
} else {
return alloca(size);
}
}
This is even more confusing for me since apparently (s)brk
can do such checks. From man 2 sbrk
:
brk() sets the end of the data segment to the value specified by addr, when that value is reasonable, the system has enough memory, and the process does not exceed its maximum data size (see setrlimit(2)).
So if (s)brk
can do such checks, then why can't alloca
?