malloced array VS. variable-length-array [duplicate]

懵懂的女人 提交于 2019-11-26 15:21:17

问题


This question already has an answer here:

  • What's the difference between a VLA and dynamic memory allocation via malloc? 4 answers

There are two ways to allocate memory to an array, of which the size is unknown at the beginning. The most common way is using malloc like this

int * array;
... // when we know the size
array = malloc(size*sizeof(int));

But it's valid too in C99 to define the array after we know the size.

... // when we know the size
int array[size];

Are they absolutely the same?


回答1:


No they're not absolutely the same. While both let you store the same number and type of objects, keep in mind that:

  • You can free() a malloced array, but you can't free() a variable length array (although it goes out of scope and ceases to exist once the enclosing block is left). In technical jargon, they have different storage duration: allocated for malloc versus automatic for variable length arrays.
  • Although C has no concept of a stack, many implementation allocate a variable length array from the stack, while malloc allocates from the heap. This is an issue on stack-limited systems, e.g. many embedded operating systems, where the stack size is on the order of kB, while the heap is much larger.
  • It is also easier to test for a failed allocation with malloc than with a variable length array.
  • malloced memory can be changed in size with realloc(), while VLAs can't (more precisely only by executing the block again with a different array dimension--which loses the previous contents).
  • A hosted C89 implementation only supports malloc().
  • A hosted C11 implementation may not support variable length arrays (it then must define __STDC_NO_VLA__ as the integer 1 according to C11 6.10.8.3).
  • Everything else I have missed :-)


来源:https://stackoverflow.com/questions/16672322/malloced-array-vs-variable-length-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!