title: how to clean up allocated memory in C?
body: <p>I wrote the following toy program and observed that the second variable <strong>test2</strong> will take the memory address released by the first variable <strong>test1</strong>. And even if I free(test1), test2 will retain test1's fields values. I wonder how to clean up the data left behind by free() in C:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  typedef struct test_str
  {
      char name[128];
      int Id;
  } test_str;
  
  typedef test_str* mytest;
  
  int main()
  {
  
      mytest test1 = malloc(sizeof(test_str));
      printf("test1 pointer address is %p \n", test1);
      strcpy(test1-&gt;name, "hello world");
      test1-&gt;Id = 10;
  
      free(test1);
  //  test1-&gt;name = NULL;   /* this does not work */
  //  test1-&gt;Id = 0;        /* without resetting Id = 0, test2-&gt;Id will show 10 */
      test1 = NULL;         
  
      mytest test2 = malloc(sizeof(test_str));
      printf("test2 pointer address is %p, name field is %s, Id = %d \n", test2, test2-&gt;name, test2-&gt;Id);
  
      return 0;
  }
  </code></pre>
  
  <p>this is the output:</p>
  
  <blockquote>
    <p>test1 pointer address is 0x2401010<br>
    test2 pointer address is 0x2401010, name field is hello world, Id = 10</p>
  </blockquote>