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); 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; 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.).
c arrays malloc
michaelmeyer
source share