Search code examples
cundefined-behaviorfree

What happens if you call free() on non allocated memory returned by a function


I am writing some random code and I wanted to know if there is there anything that defines how freeing memory returned like this works or if it is just undefined behavior.

struct a *get()
{
    static struct a value;

    return &value;
}

Solution

  • From free() documentation:

    If ptr is a null pointer, the function does nothing.

    The behavior is undefined if the value of ptr does not equal a value returned earlier by malloc(), calloc(), realloc(), or aligned_alloc()

    I.e. if you free the return value from your get function (which is not a null pointer), you invoke undefined behavior, as it is not a value returned from malloc or similar.