title: Pass values up through a tree in C
body: <p>I'm writing a simple parser in C and I'm not sure which is the best way to pass results up my tree as it gets evaluated.</p>
  
  <p>Here's my current code, the node struct and the walk function to evaluate the tree.</p>
  
  <pre><code>typedef struct node {
      struct node* left;
      struct node* right;
      void* data;
      Symbol type;
  } node;
  
  void* walk(node* n) {
      if (n != NULL) {
  
          if (n-&gt;type == plus) {
  
              int x = 0;
              int a = *(int*)walk(n-&gt;left);
              int b = *(int*)walk(n-&gt;right);
  
              x = a + b;
  
              return &amp;x;
  
          } else if (n-&gt;type == number) {
              return (int*)n-&gt;data;
          }
      }
      return NULL;
  }
  </code></pre>
  
  <p>From the code you can see when I add two numbers together I'm storing the result in a local variable and returning the address to that variable, I know this is undefined behaviour, so I thought about using malloc and changing my code to this:</p>
  
  <pre><code>int* x = malloc(1 * sizeof(int));
  int a = *(int*)walk(n-&gt;left);
  int b = *(int*)walk(n-&gt;right);
  
  *x = a + b;
  
  return x;
  </code></pre>
  
  <p>But the problem with this code is, I'm not sure what is the best way to free this memory I just malloc'd. </p>
  
  <p>Should I walk the tree a second time and free all of the memory that way or is the a better way to free the memory when I'm done or is there a better way to propagate values through my tree?</p>