关于alloca()函数

来源:互联网 发布:log4j linux 日志路径 编辑:程序博客网 时间:2024/05/21 17:10

转自:

http://mqjing.blogspot.com/2008/07/c-alloca.html

http://stackoverflow.com/questions/1018853/why-is-alloca-not-considered-good-practice


注意事項:  我想如果你想使用 alloca, 你應該要看一下

1.  http://www.gnu.org/software/libtool/manual/libc/Disadvantages-of-Alloca.html

2.  8.27 alloca() 是什麼?為什麼不提倡使用它

 

這東西比 new 或 malloc 快多了, 因為上面的兩個 functions 都是使用 heap 的方式建立記憶體,

以我有限的知識來說, 這是最慢而且相當耗資源的方法.

最重要的是你還可能忘記釋放記憶體, 造成 memory leak 的問題.

 

而 alloca 直接在 stack 上配置記憶體, 所以不用特別呼叫 free 或 del, 離開 function 後, 自動歸還.

對於暫存資料方面, 相當方便好用.

例如: 你的資料需要一連串的動作才會產生出來,  那麼中間資料的空間就可以用這玩意兒幫你配置. 相當有效率.

-----------------------------------------------------------------------------------

使用上, 必須注意的是用 alloca 配置的記憶體在 function 結束後, 就會消失.

-----------------------------------------------------------------------------------

 

所以如果你的資料還要留著繼續後面的處理時,

請使用參考延伸閱讀 1 等記憶體配置技巧.

 

下面是最簡單的範例:

  alloca.cpp  完整專案

 

回家試試看, 看能不能使你的程式更有效率. Enjoy.


=========================================


Stackoverflow

Q: 

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.

So, my question is that in spite of the above features still alloca use is discouraged, why?

A: 

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.

=========================================

【yasi】不同于大家常用的malloc()家族函数在堆上分配内存,并且需要程序员自己释放申请的内存,alloca()在栈上分配内存,出栈时自动释放。

好处是,自动释放内存,这解决了C语言一大诟病。坏处是,一旦栈上内存耗尽,程序的行为将不可预期。

建议:在可控范围内使用(即,确保绝对不会造成栈上内存耗尽的情况),而不要滥用。另外注意,出栈后,先前用alloca()分配的空间的指针不可再用。


0 0
原创粉丝点击