Why is the use of alloca() not considered good practice?
alloca()
allocates memory from Stack rather than heap which is case in malloc()
. So, when I return from the routine the memory is freed. So, actually this solves my problem of freeing up of dynamically allocated memory. Freeing of memory allocated through malloc()
is a major headache and if somehow missed leads to all sorts memory problems.
Why is the use of alloca()
discouraged in spite of the above features?
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.
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.
链接地址: http://www.djcxy.com/p/79838.html上一篇: 内存中的字符串文字是什么? 堆栈/堆?