c - malloced array VS. variable-length-array -


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't free() 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

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -