Search code examples
c

What does "pointer being freed was not allocated" mean exactly?


I have trouble with a program where I'm trying to copy a string to a structs string variable in C. After copying the string I'm trying to free the temporary string variable which is copied to the structs string variable. But when I try to free the string the program turns on me and says that "pointer being freed was not allocated". I don't understand exactly what is going on.

char str[]="       ";           //temporary string to copy to structs string
str[3]=s;                       //putting a char s in middle
strcpy(matrix[i-1][j].c, str);  //copying the string
free(str);                      //freeing str that now is useless when copied

Solution

  • 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.