title: Is there a way to set all the pointers pointing to the freed memory to NULL?
body: <p>I want to set all the pointers pointing to a freed memory location to NULL, so that no dangling pointers or double frees are possible. Is this possible in C?</p>
  
  <p>For example, I have the following structures:</p>
  
  <pre><code>struct B {
      int *arr;
      unsigned int len;
  };
  
  struct A {
      struct B *b;
  };
  
  // Freeing and setting them to NULL:
  bool test_safe_free() {
      struct A *a = malloc(sizeof(struct A));
      struct B *b = malloc(sizeof(struct B));
      b-&gt;arr = malloc(100 * sizeof(int));
      b-&gt;len = 100;
      a-&gt;b = b;
  
      safe_free_A(&amp;a);
      return a == NULL &amp;&amp; b == NULL;
  }
  
  void safe_free_B(struct B **b_ref) {
      if (*b_ref != NULL) free((*b_ref)-&gt;arr);
      (*b_ref)-&gt;arr = NULL;
      free(*b_ref);
      *b_ref = NULL;
  }
  
  void safe_free_A(struct A **a_ref) {
      // Before freeing A, freeing B:
      if (*a_ref != NULL) safe_free_B(&amp;((*a_ref)-&gt;b));
      free(*a_ref);
      *a_ref = NULL;
  }
  </code></pre>
  
  <p>The <code>test_safe_free</code> function returns false, because even though the variable <code>a</code> is set to NULL after freeing, <code>b</code> is still pointing the freed memory, because the pointer is copied (and the copy is set to NULL, while the original remains the same) when <code>a</code> passed into the function.</p>
  
  <p>I couldn't come up with a way, a structure to resolve this, but I'm also not sure whether what I'm trying to do is even possible.  </p>