Alloca()在堆栈上分配内存,而不是像malloc()那样在堆上分配内存。因此,当我从例程返回时,内存被释放。这实际上解决了动态分配内存的问题。通过malloc()释放分配的内存是一个非常令人头痛的问题,如果以某种方式错过释放会导致各种内存问题。
尽管有上述特性,为什么不鼓励使用alloca() ?
Alloca()在堆栈上分配内存,而不是像malloc()那样在堆上分配内存。因此,当我从例程返回时,内存被释放。这实际上解决了动态分配内存的问题。通过malloc()释放分配的内存是一个非常令人头痛的问题,如果以某种方式错过释放会导致各种内存问题。
尽管有上述特性,为什么不鼓励使用alloca() ?
当前回答
老问题了,但是没有人提到它应该被可变长度数组取代。
char arr[size];
而不是
char *arr=alloca(size);
它存在于标准C99中,并作为编译器扩展存在于许多编译器中。
其他回答
alloca() is very useful if you can't use a standard local variable because its size would need to be determined at runtime and you can absolutely guarantee that the pointer you get from alloca() will NEVER be used after this function returns. You can be fairly safe if you do not return the pointer, or anything that contains it. do not store the pointer in any structure allocated on the heap do not let any other thread use the pointer The real danger comes from the chance that someone else will violate these conditions sometime later. With that in mind it's great for passing buffers to functions that format text into them :)
答案就在手册页中(至少在Linux上):
返回值 函数的作用是:返回一个指向对象开头的指针 分配空间。如果 分配的原因 堆栈溢出,程序行为未定义。
这并不是说它永远不应该被使用。我工作的一个OSS项目广泛使用它,只要你不滥用它(分配巨大的值),它是好的。一旦超过了“几百字节”的标记,就应该转而使用malloc和friends。您可能仍然会遇到分配失败,但至少您会得到一些失败的指示,而不是仅仅耗尽堆栈。
Alloca()很好,很有效……但它也被深深打破了。
broken scope behavior (function scope instead of block scope) use inconsistant with malloc (alloca()-ted pointer shouldn't be freed, henceforth you have to track where you pointers are coming from to free() only those you got with malloc()) bad behavior when you also use inlining (scope sometimes goes to the caller function depending if callee is inlined or not). no stack boundary check undefined behavior in case of failure (does not return NULL like malloc... and what does failure means as it does not check stack boundaries anyway...) not ansi standard
在大多数情况下,您可以使用局部变量和主要大小来替换它。如果它用于大型对象,将它们放在堆上通常是一个更安全的想法。
如果你真的需要它,你可以使用VLA(在c++中没有VLA,太糟糕了)。在作用域行为和一致性方面,它们比alloca()要好得多。在我看来,VLA是一种正确的分配。
当然,使用所需空间的主要部分的本地结构或数组仍然更好,如果没有这样的主要堆分配,则使用普通malloc()可能是明智的。 我没有看到你真的真的需要alloca()或VLA的用例。
为什么没有人提到GNU文档中介绍的这个例子?
https://www.gnu.org/software/libc/manual/html_node/Advantages-of-Alloca.html
使用longjmp自动完成的非本地退出(参见非本地退出) 方法退出时释放使用alloca分配的空间 调用alloca的函数。这是使用的最重要的原因 alloca
建议阅读顺序1->2->3->1:
https://www.gnu.org/software/libc/manual/html_node/Advantages-of-Alloca.html 来自非本地出口的介绍和详细信息 Alloca例子
实际上,alloca并不保证使用堆栈。 事实上,gcc-2.95的alloca实现使用malloc本身从堆中分配内存。此外,这个实现是有bug的,它可能会导致内存泄漏和一些意想不到的行为,如果你在一个块内调用它进一步使用goto。并不是说您永远都不应该使用它,但有时alloca会导致比它从me中释放更多的开销。