Why is the use of alloca() not considered good practice?
One of the most memorable bugs I had was to do with an inline function that used alloca
. It manifested itself as a stack overflow (because it allocates on the stack) at random points of the program's execution.
In the header file:
void DoSomething() {
wchar_t* pStr = alloca(100);
//......
}
In the implementation file:
void Process() {
for (i = 0; i < 1000000; i++) {
DoSomething();
}
}
So what happened was the compiler inlined DoSomething
function and all the stack allocations were happening inside Process()
function and thus blowing the stack up. In my defence (and I wasn't the one who found the issue; I had to go and cry to one of the senior developers when I couldn't fix it), it wasn't straight alloca
, it was one of ATL string conversion macros.
So the lesson is - do not use alloca
in functions that you think might be inlined.
The answer is right there in the man
page (at least on Linux):
RETURN VALUE The alloca() function returns a pointer to the beginning of the allocated space. If the allocation causes stack overflow, program behaviour is undefined.
Which isn't to say it should never be used. One of the OSS projects I work on uses it extensively, and as long as you're not abusing it (alloca
'ing huge values), it's fine. Once you go past the "few hundred bytes" mark, it's time to use malloc
and friends, instead. You may still get allocation failures, but at least you'll have some indication of the failure instead of just blowing out the stack.
Old question but nobody mentioned that it should be replaced by variable length arrays.
char arr[size];
instead of
char *arr=alloca(size);
It's in the standard C99 and existed as compiler extension in many compilers.