Search code examples
carraysmallocfreeinitializer

Difference between using malloc and initializer for array?


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?


Solution

  • 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 define rgba:

    • If your definition is outside any function, or if you add static to the definition, rgba is allocated in the static area, and gets either static or global visibility
    • If you declaration is inside a function, then the memory is allocated in the automatic area (also known as "on the stack").

    Since calls of free may be passed only pointers returned by a function from the malloc family (malloc/calloc/realloc) or other functions that return dynamic memory (e.g. strdup), calling free on non-malloc-ed pointer is undefined behavior.