title: Proper Way to Cleanup in a Function with Multiple Return Points
body: <p>I have a recursive search algorithm, and I want to clean up my pointers after each call. However, I return in so many locations, it seems sloppy to put a <code>delete</code> or <code>free</code> before every one.</p>
  
  <p>Is there a better way? Does me freeing them all at return of the function mean I should just allocate them on the stack instead of in the heap?</p>
  
  <p>Note this is a parallel search (not shown in code), but the caller will never return before its children. Does this have any additional pitfalls for using the stack?</p>
  
  <p><strong>Example Code (Don't worry about the algorithm here):</strong></p>
  
  <pre><code>//create a new struct state (using new), initialize and return (C style)
  new_state()
  
  free_list(state* node)//free a list
  
  double minimax(state* node, state* bestState) {
  
      if (base_case) {
          return;
      }
  
      state* gb = new_state(); //single node
      state* children = new_state(); //head of list
  
      generate_children(children); //fill list
  
      state* current = children; //traverse node
  
      //recurse on child
      double result = -minimax(current, gb);
  
      if (case1) {
          free(gb);
          free_list(children);
          return;
      }
      if (case2)  {
          //do stuff
      }
  
      while(current != NULL){
          result = -minimax(current, gb);
          if (case1) {
              free(gb);
              free_list(children);
              return;
          }
          if (case2)  {
              //do stuff
          }
          current = current-&gt;next;
      }
      free(gb);
      gb = NULL;
  
      //More stuff (with children but not gb)
      free_list(children);
      return;
  }
  </code></pre>