本文介绍了为什么使用 alloca() 不被认为是好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

alloca() 在堆栈上而不是在堆上分配内存,就像 malloc() 的情况一样.因此,当我从例程返回时,内存被释放.所以,实际上这解决了我释放动态分配内存的问题.释放通过 malloc() 分配的内存是一个令人头疼的问题,如果以某种方式错过会导致各种内存问题.

alloca() allocates memory on the stack rather than on the heap, as in the case of malloc(). So, when I return from the routine the memory is freed. So, actually this solves my problem of freeing up dynamically allocated memory. Freeing of memory allocated through malloc() is a major headache and if somehow missed leads to all sorts of memory problems.

尽管具有上述特性,为什么不鼓励使用 alloca()?

Why is the use of alloca() discouraged in spite of the above features?

推荐答案

答案就在 man 页面(至少在 Linux):

The answer is right there in the man page (at least on Linux):

返回值alloca() 函数返回一个指向开头的指针分配的空间.如果分配原因堆栈溢出,程序行为未定义.

这并不是说它不应该被使用.我参与的其中一个 OSS 项目广泛使用它,只要你不滥用它(alloca'ing 巨大的价值),就可以了.一旦超过几百字节"标记,就该使用 malloc 和朋友了.您可能仍然会遇到分配失败的情况,但至少您会有一些失败的迹象,而不仅仅是堆栈溢出.

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.

这篇关于为什么使用 alloca() 不被认为是好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 13:50
查看更多