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?