title: Free dynamically allocated memory from 2D array within a struct
body: <p>I have a pointer to a struct and one of the objects in the struct is a int **. The double pointer is used to dynamically allocate memory for a 2d array. I am having trouble figuring out how to free the memory for this array. Any ideas?</p>
  
  <pre><code>struct time_data {
      int *week;
      int *sec;
      int **date;
  };
  typedef struct time_data time_data;
  
  time_data *getTime(time_data *timeptr, int rows, int cols) {
      int i = 0;
      time_data time;
  
      // allocate memory for time.date field
      time.date = (int **)malloc(rows*(sizeof(int *))); // allocate rows
      if(time.date == NULL)
          printf("Out of memory\n");
      for(i=0; i&lt;rows; i++) {
          time.date[i] = (int *)malloc(cols*sizeof(int));
          if(time.date[i] == NULL)
              printf("Out of memory\n");
      }
      timeptr = &amp;time;
      return timeptr;
  }
  
  int main(int argc, const char * argv[]) {
      time_data *time = NULL;
      int rows = 43200, cols = 6;
      int i;
      time = getTime(time, rows, cols);
  
      for(i=0; i&lt;rows; i++)
          free(time-&gt;date[i]); // problem here
      free(time-&gt;date);
  
  }
  </code></pre>
  
  <p>Modified Version (in case anyone else has similar issue)</p>
  
  <pre><code>    struct time_data {
      int *week;
      int *sec;
      int **date;
  };
  typedef struct time_data time_data;
  
  time_data *getTime(int rows, int cols) {
      int i = 0;
      time_data *time = malloc(sizeof(*time));
  
      // allocate memory for time.date field
      time-&gt;date = (int **)malloc(rows*(sizeof(int *))); // allocate rows
      if(time-&gt;date == NULL)
          printf("Out of memory\n");
  
      for(i=0; i&lt;rows; i++) {
          time-&gt;date[i] = (int *)malloc(cols*sizeof(int));
          if(time-&gt;date[i] == NULL)
              printf("Out of memory\n");
      }
      return time;
  }
  
  int main(int argc, const char * argv[]) {
      time_data *time = NULL;
      int rows = 43200, cols = 6;
      int i;
      time = getTime(rows, cols);
  
      for(i=0; i&lt;rows; i++)
          free(time-&gt;date[i]); // problem here
      free(time-&gt;date);
  return 0;
  }
  </code></pre>