Here is my code. I try to malloc the element that been malloc, and I don't know how to free them.
char *d = "apple";
int main() {
char *a = malloc(10 * sizeof(char));
char **b = &a;
strcpy(a,d);
printf("%c", *b[0]);
b[0] = malloc(3 * sizeof(char));
free(b[0]);
free(a);
}
After
b[0]is the same asa. So when you doyou're replacing the value of
awith this new allocation.Then
free(b[0])is the same asfree(a);. So if you do both of these, you're freeing the same memory twice, which is a double free.You've also leaked the original allocation that was assigned to
a, since you no longer have a pointer to that. You need another variable to save that, so you can free it.