I have trouble with a program where im trying to copy a string to a structs string variable in c. After copying the string im 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
Only pointers returned by calls to
malloc(),realloc()orcalloc()can be passed tofree()(dynamically allocated memory on the heap). From section 7.20.3.2 The free function of C99 standard:In the posted code,
stris not dynamically allocated but is allocated on the stack and is automatically released when it goes out of scope and does not need to befree()d.