title: ASAN heap use after free
body: <p>I am running ASAN for finding memory leaks in a very big project. I have found out the cause, but do not know how to resolve it. I have made a sample program to make the problem understandable.
  In the below program I can only work-around on specified code. For rest of the code it is not possible to do work around.
  So please suggest what work around I may have to resolve below ASAN error.
  (How to make pointer two as NULL using t1?)</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  
  typedef struct l
  {
      int a, b;
  }pack;
  
  void delete_me(pack *ap)
  {
      free(ap);
  }
  
  int main(void)
  {
      pack **d_ptr = (pack **)malloc(3 * sizeof(pack *));
      pack *one, *two, *three;
      one = (pack *)malloc(sizeof(pack));
      one-&gt;a = 1, one-&gt;b = 2;
      two = (pack *)malloc(sizeof(pack));
      two-&gt;a = 3, two-&gt;b = 4;
      three = (pack *)malloc(sizeof(pack));
      three-&gt;a = 5, three-&gt;b = 6;
      d_ptr[0] = one;
      d_ptr[1] = two;
      d_ptr[2] = three;
  
      // I can Only work-around below code (4 lines)
      pack *t1 = d_ptr[1]; // For which index t1 would be assigned, is not known before hand
      t1-&gt;a = 1; t1-&gt;b = 2;
      printf("a: %d, b: %d\n", two-&gt;a, two-&gt;b);
      delete_me(t1); // How to delete t1 so that corresponding pointer also becomes NULL?
      // Work around only till here was possible.
  
      // Below this, No workaround possible.
      if (two &amp;&amp; (two-&gt;a == one-&gt;a)) // ASAN ERROR
              printf("ERROR\n");
      else
              printf("It works!\n");
      return 0;
  }
  </code></pre>
  
  <p>ASAN Error:
  ERROR: AddressSanitizer: heap-use-after-free  </p>