C ++:本地数组定义与一个malloc调用 [英] c++: local array definition versus a malloc call

查看:156
本文介绍了C ++:本地数组定义与一个malloc调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是什么的区别是:

somefunction() {  
    ...  
    char *output;   
    output = (char *) malloc((len * 2) + 1);  
    ...  
}  

和这样的:

somefunction() {  
    ...  
    char output[(len * 2) + 1];  
    ...  
}  

当是其中一个比另一个更合适?

When is one more appropriate than the other?

感谢大家的答案。这里是一个总结:

thanks all for your answers. here is a summary:


  1. 恩。 1是堆分配

  2. 恩。 2是堆栈分配

  3. 还有就是堆栈上的大小限制,将其用于较小的分配

  4. 您可以免费堆分配,否则会泄露

  5. 的堆栈分配是无法访问的,一旦函数退出

  6. 堆分配是可访问的,直到你释放它(或应用端)

  7. VLA的不是标准C ++的一部分

修正的欢迎。

这里是VS叠层堆之间的差的一些说明:搜索
<一href=\"http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap/79936#79936\">http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap/79936#79936

here is some explanation of the difference between heap vs stack:
http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap/79936#79936

推荐答案

使用当地人当你只有一个小数据量,你不打算使用你已经宣布它的功能范围以外的数据如果你要通过周围的数据,使用malloc。

Use locals when you only have a small amount of data, and you are not going to use the data outside the scope of the function you've declared it in. If you're going to pass the data around, use malloc.

局部变量保持堆栈,这是更为大小比堆,其中使用malloc分配的数组去上有限。我通常去什么>被提上堆16个字节,但你有比这一点更灵活。只是不要在KB / MB大小的范围内分配当地人 - 他们属于堆

Local variables are held on the stack, which is much more size limited than the heap, where arrays allocated with malloc go. I usually go for anything > 16 bytes being put on the heap, but you have a bit more flexibility than that. Just don't be allocating locals in the kb/mb size range - they belong on the heap.

这篇关于C ++:本地数组定义与一个malloc调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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