cdouble-free

Why I get double free?


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);
}

Solution

  • After

    char **b = &a;
    

    b[0] is the same as a. So when you do

    b[0] = malloc(3 * sizeof(char));
    

    you're replacing the value of a with this new allocation.

    Then free(b[0]) is the same as free(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.

    char *d = "apple";
    int main() {            
      char *a = malloc(10 * sizeof(char));
      char **b = &a;
      strcpy(a,d);
      printf("%c", *b[0]);
      char *c = a; // save a before overwriting it below
      b[0] = malloc(3 * sizeof(char));
      free(b[0]);
      free(c);
    }