I have the code below in a main.c file:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct mystruct {const char *name; int x;};
char *test_calloc_char_p(const char *char_p) {
return (char *) calloc(1, (strlen(char_p) + 1) * sizeof(char));
}
int main(void) {
struct mystruct *ms1;
ms1 = (struct mystruct *) calloc(1, sizeof(struct mystruct));
ms1->name = test_calloc_char_p("dlldffdl");
ms1->x = 3;
free(&ms1->name);
free(ms1);
return 0;
}
Which I compile with gcc main.c -o test
and run with ./test
, and I get:
free(): double free detected in tcache 2
Abortado
I don't understant, why? I should not release ms1->name
? because when I comment this line I don't get the error, but why shouldn't I release something that I allocated?
This is incorrect:
free(&ms1->name);
The address of ms1->name
is part of the allocated memory assigned to ms1
. it is not the allocation for the name
member.
You assigned allocated memory to ms1->name
, so that is what you should pass to free
:
free((char *)ms1->name);
Note that the cast is needed because otherwise you would be passing a const
pointer to a function expecting a non-const
pointer. The cast can be removed by changing the name
member from const char *
to char *
.