Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Sized Arrays vs calloc in C

On the discussion of dynamic memory here: "Intro to C Pointers and Dynamic Memory"

The author states:

A memory block like this can effectively be used as a more flexible array. This approach is actually much more common in real-world C programs. It's also more predictable and flexible than a "variable size array"

The type of memory block he is talking about is as such:

const int size = 5;
int * array = calloc(size, sizeof(int));

and then using another pointer to iterate over the array:

int * index = array;
for (i = 0; i < size; i++) {
    *index = 1; // or whatever value
    index++;
}

My question is how is this method better than a standard variable sized array like this?:

int array[variable];

or dynamic:

char name[] = "Nick";

The author doesn't really shed much light as to why I should prefer the former method to the latter. Or more specifically: How is it more "predictable and flexible"?

like image 939
nmiller Avatar asked Jan 15 '09 23:01

nmiller


People also ask

Are variable length arrays bad C?

Safe and useful variable length arrays It's convenient and useful because it makes some expressions simpler. It's safe because there's no arbitrary stack allocation. Pointers to arrays are a rare sight in C code, whether variable length or not.

What is the difference between variable length array and dynamic memory allocation?

Allocation: VLAs are allocated on the stack, whereas dynamic arrays are allocated on the heap. So, VLAs are faster than dynamic memory. Since the compiler has to cleanup memory (for dynamic array) after usage.

Are there dynamic arrays in C?

We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.

Where is a variable length array guaranteed to be stored?

The data for the variable length arrays in a table is not stored in the actual data records; it is stored in a special data area, the heap , following the last fixed size data record.


2 Answers

If you declare int array[variable] the memory will be allocated on the stack which is not very good for large, relatively permanent data structures (such as one you might want to return). You don't need to free memory manually if you use the array syntax since it's freed when it goes out of scope. calloc on the other hand will allocate memory dynamically at run time on the heap. You'll have to free it yourself as soon as you're finished with it.

like image 82
mmx Avatar answered Sep 24 '22 21:09

mmx


I agree with ocdecio that c89 doesn't allow

int array[variable]

c99 allows some types of variables and expressions to be the array size. But in addition to that, things allocated with malloc and family can be resized using realloc.

like image 24
Evan Teran Avatar answered Sep 20 '22 21:09

Evan Teran