Why do I have to free
an array created using malloc, but not one created using an initializer?
float* rgba = malloc(4 * sizeof(float));
free(rgba);
versus:
float rgba[] = { 0.0f, 0.0f, 0.0f, 0.0f };
free(rgba); // ERROR
What is happening under the hood here in the second one?
The difference is that
malloc
always allocates memory from the dynamic memory, while initializer places the data in either the static or the automatic memory, depending on the context where you definergba
:static
to the definition,rgba
is allocated in the static area, and gets either static or global visibilitySince calls of
free
may be passed only pointers returned by a function from themalloc
family (malloc
/calloc
/realloc
) or other functions that return dynamic memory (e.g.strdup
), callingfree
on non-malloc-ed pointer is undefined behavior.