title: How to prevent dangling pointers/junk in c?
body: <p>I'm new to C and haven't really grasped when C decides to free an object and when it decides to keep an object.</p>
  
  <p>heap_t is pointer to a struct heap.</p>
  
  <pre><code>heap_t create_heap(){
      heap_t h_t = (heap_t)malloc(sizeof(heap));
      h_t-&gt;it = 0;
      h_t-&gt;len = 10;
      h_t-&gt;arr = (token_t)calloc(10, sizeof(token));
      //call below a couple of times to fill up arr
      app_heap(h_t, ENUM, "enum", 1);
      return h_t;
  }
  </code></pre>
  
  <p>putting h_t through</p>
  
  <pre><code>int app_heap(heap_t h, enum symbol s, char* word, int line){
      int it = h-&gt;it;
      int len = h-&gt;len;
  
      if (it + 1 &lt; len ){
          token temp;
          h-&gt;arr[it] = temp;
          h-&gt;arr[it].sym = s;
          h-&gt;arr[it].word = word;
          h-&gt;arr[it].line = line;
          h-&gt;it = it + 1;
          printf(h-&gt;arr[it].word);
          return 1;
      } else {
          h-&gt;len = len*2;
          h-&gt;arr = realloc(h-&gt;arr, len*2);
          return app_heap(h, s, word, line);
      }
  
  }
  </code></pre>
  
  <p>Why does my h_t->arr fill up with junk and eventually I get a segmentation fault? How do I fix this?  Any C coding tips/styles to avoid stuff like this?</p>