title: Free pointer to an array
body: <p>In my program I have a structure that looks like this:</p>
  <pre><code>struct structure {
      int n;
      int *arr;
  };
  </code></pre>
  <p>And I allocate memory for arr like this:</p>
  <pre><code>structure-&gt;arr = malloc(sizeof(int) * arr_size);
  </code></pre>
  <p>Now here is where I start to get confused, and I am not sure if I am doing it right. What I want to do is use &quot;arr&quot; as an array to store or access integers. So I set arr to point to an array that I created and filled with 0's:</p>
  <pre><code>int new_arr[i];
  structure.arr = new_arr;
  </code></pre>
  <p>I am not sure if this is right, but so far I don't get any errors. So I create another array that stores these structures, and I insert some new structures in it. But when I try to free the member arr from any of the structures inside the array (like this <code>free(&amp;array_of_struct[i].arr);</code>) I get an error:</p>
  <pre><code>==747==ERROR: AddressSanitizer: attempting free on address which was not malloc()-ed: 0x7fffd7c6ad08 in thread T0
  
  SUMMARY: AddressSanitizer: bad-free (/lib/x86_64-linux-gnu/libasan.so.5+0x10d7cf) in __interceptor_free
  ==747==ABORTING
  </code></pre>
  <p>So I think I understand what the problem is, but I have no idea how to solve it. I don't imagine this is the way I'm supposed to point to an array, so can anyone tell me how to do it right?</p>
  <p><strong>UPDATE</strong></p>
  <p>So instead of writing &quot;structure.arr = new_arr&quot; I am now using memset this way:</p>
  <pre><code>memset(structure.arr, '\0', array_size * sizeof(int));
  </code></pre>
  <p>But I still get the same arror when trying to free structure.arr. Also if I try to use mempcy. Could there be something wrong with <code>free(&amp;array_of_struct[i].arr)</code>?</p>
  <p><strong>UPDATE2</strong></p>
  <p>So I actually managed to use mempcy and free member &quot;arr&quot;. The problem is, that I can only do it before I append the structure to my array of structures. If I try to free it after that (as a member of the array) I get the errors.</p>
  <p><strong>LAST UPDATE</strong></p>
  <p>I have managed to make it work with memset. The problem was that I had to write <code>free(array_of_struct[i].arr)</code> instead of <code>free(&amp;array_of_struct[i].arr)</code>
  Thank you all for the help.</p>