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.).