title: Using free() on non-heap objects in C
body: <p>I couldn't find what the behaviour of this action actually is. <br/>It doesn't seem to cause any run-time errors so I guess it just does nothing? <br/><br/>I found about this technique only recently while I was writing my coursework. <br/>Actually, my professor seems to be an advocate of this but I fail to grasp how it works without breaking. <br/>Basically, the idea is to use a variable as a test object or guard for a struct pointer, and then pass this "dummy" variable to a function. <br/>I'll try giving an example with code: <br></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  struct Struct {
      int a;
      struct Struct *next;
      float c;
  };
  
  int
  stuff(struct Struct *ptr) {
      free(ptr);
      return 1; // always assume true for the sake of example
  }
  
  int
  main(int argc, char *argv[]) {
      struct Struct *ptr;
      struct Struct test;
      int retval;
  
      if ((ptr = malloc(sizeof(struct Struct *))) == NULL) {
          fprintf(stderr, "ERROR: could not allocate memory\n");
          return -1;
      }
  
      // some magic goes here...
      test = *ptr;
      retval = stuff(&amp;test);
      if (retval) {
          free(ptr);
      }
  
      return 0;
  }
  </code></pre>
  
  <p>In my coursework I had to free a struct's two struct pointer members one after another, and then free the struct's memory. Since either of the struct pointer members could be operating on data, if one could not be freed then the whole main struct should not be freed and changes should be reverted. <br/>This approach of a variable on the stack to work out whether memory can be safely freed without compromising running data is what's baffling me. I'm not really sure what I'm even not understanding. <br/>Would anyone aware of this methodology enlighten me on the details?</p>