Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

c - What's the difference between a VLA and dynamic memory allocation via malloc?

I was curious with this:

What is the diference between:

const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);

and:

char Buffer[MAX_BUF];
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • Case 1: In

     char Buffer[MAX_BUF];
    

    Buffer is an array of size MAX_BUF. The allocation technique is called VLA.

  • Case 2: In

    const int MAX_BUF = 1000;
    char* Buffer = malloc(MAX_BUF);
    

    Buffer is a pointer which is allocated a memory of size MAX_BUF which is 1000.

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) 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]

Note: Wiki

For example, the GNU C Compiler allocates memory for VLAs on the stack.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...