title: How to free memory of a double pointer in this case properly?
body: <p>My program is to increase a size of a struct array by creating new arr with a new size then assign the double pointer of the old array to the new one. I have been struggling with releasing memory of the old array before or after assigning it to the new one. If I don't fee(), it gives correct results, otherwise, it automatically pickup and print out some trash values. Please help, Thank you.</p>
  
  <p>*realloc is not allowed.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  struct car {
      char name[30];
      int quantity;
  };
  
  void increaseSize(int *cap, int size, struct car **carArray) {
      printf("cap = %d size = %d\n", *cap, size);
      *cap *= 2;
      printf("cap x 2 = %d\n", *cap);
      struct car *newCarArray = (struct car * ) malloc(*cap * sizeof(struct car));
      memcpy(newCarArray, carArray, sizeof(struct car));
      free(*carArray); // If I free old carArray here, it will give incorrect results. How can I release/clear/delete/free the memory of the old array here?
      carArray = &amp;newCarArray;
      printf("increased cap = %d size = %d\n", *cap, size);
  }
  
  void printArray(int cap, int size, struct car *carArray) {
      printf("Capacity = %d, Size = %d \n", cap, size);
      for(int i = 0; i &lt; size; i++) {
          printf("Car %d, Name: %s, Quantity: %d\n", i, carArray[i].name, carArray[i].quantity);
      }
  }
  
  int main() {
  
      int cap = 2;
      int size = 0;
      struct car *carArray = (struct car *) malloc(cap * sizeof(struct car));
  
      struct car car_0 = {"Corolla", 5};
      carArray[0] = car_0;
      size++;
  
      struct car car_1 = {"Accord", 8};
      carArray[1] = car_1;
      size++;
  
      printArray(cap, size, carArray);
  
      increaseSize(&amp;cap, size, &amp;carArray);
  
      struct car car_2 = {"Forte", 3};
      carArray[2] = car_2;
      size++;
  
      printArray(cap, size, carArray);
      free(carArray);
  
      return 0;
  }
  </code></pre>