它是用C99 VLA相比的malloc /自由是个好主意? [英] Is it a good idea to use C99 VLA compared to malloc/free?

查看:193
本文介绍了它是用C99 VLA相比的malloc /自由是个好主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是用C99 VLA一个好主意?什么时候适合使用VLA相比的malloc /免费的吗? (因为VLA可能炸毁堆栈?)

Is it a good idea to use C99 VLA? When is it appropriate to use VLA compared to malloc/free? (since VLA may blow up stack?)

推荐答案

是的,除非在你知道自己的堆栈可以炸毁的情况。您也可以在必要时更改堆栈的大小,这是多么不同的每个操作系统上,但它是可能的。
VLA的优点是:

Yes, except in cases where you know your stack can blow up. You can also change the size of the stack if necessary, it's different how on every OS but it's possible. The advantages of VLA are:


  • 快速:调整堆栈指针和/或帧指针会一直做反正所以VLA的成本几乎为0

  • Fast : adjusting the stack pointer and/or the frame pointer would have been done anyway so the cost of a VLA is nearly 0.

简单:一个简单的定义,没有指针进行初始化,检查释放,没有内存泄漏的风险

Easy : a simple definition, no pointer to initialize, to check to free and no risk of memory leaks.

因为每个线程都有自己的堆栈它会自动线程安全的。它也有更好的缩放,因为没有必要锁定,可以使用的malloc /免费

It's automatically thread safe as each thread has its own stack. It has also better scaling as there's no need of locking, one problem that can arise when using malloc/free.

读:这真是一个简单的概念,所以不太可能引入微妙的错误

Readable : it's really a simple concept, so less likely to introduce subtle bugs.

它也有一些缺点:


  • 大小的限制:前面已经说过,堆栈可以炸毁。

  • Size limited : as already said, the stack can blow up.

缓冲区溢出是比堆内存更严重一点(我们可以说,这是一个优势,作为一个崩溃的应用程序比一个默默破坏数据,并最终崩溃的不相关的指示更佳)。

Buffer overflows are a bit more serious than on heap memory (one can argue that it's an advantage, as a crashing application is better than a one silently corrupting data and eventually crashing on unrelated instructions).

可移植性:不是所有的编译器实现它,但它往往可以通过的alloca 模拟(注意语义是有点不同,但没有什么严重)。

Portability : not all compilers implement it, but it can often be simulated by alloca (attention the semantic is a little bit different but nothing really serious).

这篇关于它是用C99 VLA相比的malloc /自由是个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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