c - malloced array VS. variable-length-array -
this question has answer here:
there 2 ways allocate memory array, of size unknown @ beginning. common way using malloc
this
int * array; ... // when know size array = malloc(size*sizeof(int));
but it's valid in c99 define array after know size.
... // when know size int array[size];
are absolutely same?
no they're not absolutely same. while both let store same number , type of objects, keep in mind that:
- you can
free()
malloced array, can'tfree()
variable length array (although goes out of scope , ceases exist once enclosing block left). in technical jargon, have different storage duration: allocated malloc versus automatic variable length arrays. - although c has no concept of stack, many implementation allocate variable length array stack, while
malloc
allocates heap. issue on stack-limited systems, e.g. many embedded operating systems, stack size on order of kb, while heap larger. - it easier test failed allocation
malloc
variable length array. - malloced memory can changed in size
realloc()
, while vlas can't (more precisely executing block again different array dimension--which loses previous contents). - a hosted c89 implementation supports
malloc()
. - a hosted c11 implementation may not support variable length arrays (it must define
__stdc_no_vla__
integer 1 according c11 6.10.8.3). - everything else have missed :-)
Comments
Post a Comment