Allocating several arrays of the same type
arrays, c, malloc
Solution
It is entirely valid in C. But remember to free only the `a` pointer. Your this method is similar to struct hack
However I think one logical problem in this code is that if you go out of bounds for `a1` or `a2` you will not be able to notice it as you will be accessing valid memory addresses, i.e. you will not get Seg Fault. However, in first case you "may" get SegFault and notice your error.
Problem
I need to allocate several arrays of the same type and shape. At the beginning, 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); } ``` To avoid calling `malloc` and `free` several times, I changed the above into: ``` 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 ok (in the sense that the functions behave the same way in the real-world case), but I wonder if this is still valid C code (undefined behaviour?), and if I can extend this method to complex data kind (arrays of structs, etc.).