VLA 和通过 malloc 进行动态内存分配有什么区别? [英] What's the difference between a VLA and dynamic memory allocation via malloc?

查看:31
本文介绍了VLA 和通过 malloc 进行动态内存分配有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此很好奇:

有什么区别:

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.

      Buffer is an array of size MAX_BUF. The allocation technique is called 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 size MAX_BUF which is 1000.

      并且,数组与指针相同,并且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. (1) 在堆栈上,通常 注意,而 (2) 在堆上,总是.
      2. (1) 分配后大小固定,(2) 可以调整大小.
      3. (1) 在调用封闭函数时分配并且具有块作用域 OTOH,(2) 在运行时动态分配内存,并且返回的内存具有从分配到释放的生命周期.
      4. (1) 分配的内存不需要由程序员管理,而在(2) 中所有malloc()d 的内存应该是free()d.[礼貌:Giorgi]
      1. (1) is on stack, usually Note, while (2) is on heap, always.
      2. (1) has fixed size once allocated, (2) can be resized.
      3. (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.
      4. (1) allocated memory need not be managed by programmer, while in (2) all malloc()d memory should be free()d. [Courtesy: Giorgi]

      <小时>

      注意:维基

      例如,GNU C 编译器在堆栈上为 VLA 分配内存.

      这篇关于VLA 和通过 malloc 进行动态内存分配有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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