Selecting multiple arrays of the same type

I need to select multiple arrays of the same type and shape. At first I did something like:

void alloc_arrays_v1(size_t nmemb) { int *a1, *a2, *a3; a1 = malloc(nmemb * sizeof int); a2 = malloc(nmemb * sizeof int); a3 = malloc(nmemb * sizeof int); /* do some stuff with the arrays */ free(a1); free(a2); free(a3); } 

In order not to call malloc and free several times, I changed this to:

 void alloc_arrays_v2(size_t nmemb) { int *a, *a1, *a2, *a3; a = malloc(3 * nmemb * sizeof int); a1 = a; a2 = a1 + nmemb; a3 = a2 + nmemb; /* do some stuff */ free(a); } 

This seems to be normal (in the sense that the functions behave the same in the real case), but I wonder if this code is really valid C (undefined behavior?), And if I can extend this method refers to a complex data type (arrays structures, etc.).

+8
c arrays malloc
source share
3 answers

This is completely true in C. But remember to free only pointer a . Your method is similar to struct hack

However, I think that one logical problem in this code is that if you go beyond the limits for a1 or a2 , you will not be able to notice this, since you will be accessing valid memory addresses, i.e. you will not get Seg Fault .
However, in the first case, you can “get” SegFault and notice your mistake.

+3
source share

Both are valid since you are using malloc to allocate contiguous memory. In fact, code similar in form to the second case is often used to model matrices in C.

It is worth noting that

 int a1, a2, a3, a4; int* a = &a1; int oops = *(a + 1); 

- This behavior is undefined, since you cannot expect stack distribution to be contiguous.

+3
source share

This is absolutely true.

What you do is basically the same:

 void alloc_arrays_v1(size_t nmemb) { typedef int one_array[nmemb]; // this is one array typedef one_array three_arrays[3]; // this are three arrays one_array * a; int *a1, *a2, *a3; a = malloc(sizeof(three_arrays)); a1 = a[0]; // a[0] is a one_array, which decays into an int * here. a2 = a[1]; // the same a3 = a[2]; // as above /* do some stuff with the arrays */ free(a); } 

with the difference that the calculations are performed using arithmetic of pointers and arrays.

+2
source share

All Articles