title: How can I free memory from my structure containing an array of dynamically created strings?
body: <p>I have a struct that must contain, among other things, a dynamically created string and an array of also dynamically-created strings. However, I am finding it difficult to free this struct afterwards, as it gives me runtime errors. </p>
  
  <p>So the questions are:</p>
  
  <p>So far I cannot even release the string. Why?</p>
  
  <p>How to create a dynamic "array" of strings inside this struct?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  
  typedef struct { 
    unsigned int num;
    unsigned int* sizes;
    unsigned int* coords;
    char* name;
  } TOPOLOGY;
  
  TOPOLOGY * constructor() {
    char * name="Hardware Topology";
    TOPOLOGY * top=calloc(1,sizeof(TOPOLOGY *));
    top-&gt;num=0;
    top-&gt;name=calloc(1,strlen(name));
    strcpy(top-&gt;name,name);
    return top;
  }
  
  void destructor(TOPOLOGY * top) {
    if(top-&gt;sizes!=NULL) { free(top-&gt;sizes); }
    if(top-&gt;coords!=NULL) { free(top-&gt;coords); }
    if(top-&gt;name!=NULL) { free(top-&gt;name); } exit(0);
    if(top!=NULL) { free(top); }
  }
  
  void add(TOPOLOGY * top, unsigned int size) {
    top-&gt;num++;
    size_t s=top-&gt;num*sizeof(unsigned int*);
    top-&gt;sizes=realloc(top-&gt;sizes,s);
    top-&gt;coords=realloc(top-&gt;coords,s);
    top-&gt;sizes[top-&gt;num-1]=size;
  }
  
  void coords(TOPOLOGY * top, unsigned int coords[]) {
    int i;
    for(i=0;i&lt;top-&gt;num;i++) {
      top-&gt;coords[i]=coords[i];
    }
  }
  
  void get(TOPOLOGY * top) {
    int i;
    for(i=0; i&lt;top-&gt;num;i++) {
      printf("Dim: %d: %d\n",i,top-&gt;sizes[i]);
    }
  }
  
  void getcoords(TOPOLOGY * top) {
    int i;
    for(i=0;i&lt;top-&gt;num;i++) {
      printf("Coord %d = %d\n",i,top-&gt;coords[i]);
    }
  }
  
  void setname(TOPOLOGY * top, char * name) {
    int s=sizeof(name);
    top-&gt;name=realloc(top-&gt;name,s);
    strcpy(top-&gt;name,name);
  }
  
  
  int main() {
    unsigned int c[4]={3,2,0,1};
    TOPOLOGY * top=constructor();
    add(top,1025);
    add(top,512);
    add(top,10);
    add(top,24);
    coords(top,c);
    get(top);
    getcoords(top);
    destructor(top);
    return 0;
  }
  </code></pre>