VLA和通过malloc分配动态内存之间有什么区别? [英] What's the difference between a VLA and dynamic memory allocation via malloc?
本文介绍了VLA和通过malloc分配动态内存之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对此很好奇:
两者之间的区别是什么?
What is the diference between:
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
和:
char Buffer[MAX_BUF];
推荐答案
-
情况1:在
Case 1: In
char Buffer[MAX_BUF];
Buffer
是大小为MAX_BUF
的 数组 .分配技术称为 VLA .情况2:在
const int MAX_BUF = 1000; char* Buffer = malloc(MAX_BUF);
Buffer
是 指针 ,它分配了大小为MAX_BUF
的内存,该内存为1000
.Buffer
is a pointer which is allocated a memory of sizeMAX_BUF
which is1000
.,并且数组与指针不相同,并且 C-FAQ有一个很好的收藏,详细说明了原因.
and, an array is not the same as a pointer, and C-FAQ has a Very Good collection detailing the reasons.
就可用性和行为而言,主要区别在于:
The major difference, in terms of usability and behaviour are:
- (1)在堆栈上,通常是 Note ,而(2)总是在堆栈上.
- (1)分配后具有固定的大小,(2)可以调整大小.
- (1)是在调用封闭函数并具有块范围OTOH时分配的;(2)是在运行时动态分配的内存,并且返回的内存的生存期从分配到释放为止.
- (1)分配的内存无需由程序员管理,而在(2)中,所有
malloc()
d内存都应为free()
d. [礼貌:乔基 ]
- (1) is on stack, usually Note, while (2) is on heap, always.
- (1) has fixed size once allocated, (2) can be resized.
- (1) is allocated when the enclosing function is called and has the block scope OTOH, (2) is allocated memory dynamically, at runtime and the returned memory has a lifetime which extends from the allocation until the deallocation.
- (1) allocated memory need not be managed by programmer, while in (2) all
malloc()
d memory should befree()
d. [Courtesy: Giorgi]
注意: Wiki
Note: Wiki
例如,GNU C编译器为堆栈上的VLA分配内存.
这篇关于VLA和通过malloc分配动态内存之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文