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
mallocalways 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:staticto the definition,rgbais allocated in the static area, and gets either static or global visibilitySince calls of
freemay be passed only pointers returned by a function from themallocfamily (malloc/calloc/realloc) or other functions that return dynamic memory (e.g.strdup), callingfreeon non-malloc-ed pointer is undefined behavior.