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.
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.
本文详细解析了alloca函数在编程中的常见误解和潜在风险,并提供了避免其引发堆栈溢出的方法。通过实例分析,展示了如何正确使用alloca以避免性能问题和错误,同时介绍了在何时转向更安全的内存分配函数如malloc。特别强调了内联函数使用alloca可能导致的问题,并通过案例说明了解决策略。
2083

被折叠的 条评论
为什么被折叠?



