What does “pointer being freed was not allocated” mean exactly?

Only pointers returned by calls to malloc(), realloc() or calloc() can be passed to free() (dynamically allocated memory on the heap). From section 7.20.3.2 The free function of C99 standard:

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

In the posted code, str is not dynamically allocated but is allocated on the stack and is automatically released when it goes out of scope and does not need to be free()d.

Leave a Comment