为什么用,alloca的()没有考虑好的做法呢? [英] Why is the use of alloca() not considered good practice?

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

问题描述

的alloca()从栈中分配内存,而不是堆这是在情况的malloc()。所以,当我从常规返回内存被释放。所以,其实这解决了我腾出的动态分配的内存的问题。内存释放通过分配的malloc()是一个大难题,如果种种原因错过导致各种内存问题。

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.

为什么使用的alloca()气馁,尽管上述特点?

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

推荐答案

答案是正确的,在该页(至少在Linux上):

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

返回值
         中,alloca()函数返回一个指针的开始
  分配的空间。如果
  分配的原因
         堆栈溢出,程序行为是不确定的。

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.

这并不是说,它不应该被使用。其中一个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的()没有考虑好的做法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆