title: Is it safe to use memcpy to insert an element in an array which has greater allocated size?
body: <p>I have an array which contains a preallocated memory size for say 1000 elements.
  There is a counter to track the actual number of elements.</p>
  <p>Is it safe to use memcpy to insert an alement at a given position?</p>
  <p>If I run this, I see that it works, but I am in doubt about if it works by mere chance or it is fundamentally wrong approach as memcpy can not guarantee that the previous data is going to be preserved.</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  int main()
  {
      int *list;
      int list_size;
      
      // PREALLOCATE SPACE FOR 1000 ITEMS
      list = calloc(sizeof(int), 1000);
      list_size = 0;
      
      // ADD ITEMS
      list[0] = 2; list_size++;
      list[1] = 4; list_size++;
      list[2] = 6; list_size++;
      list[3] = 8; list_size++;
      list[4] = 10; list_size++;
      
      // LIST ITEMS
      printf(&quot;---\n&quot;); for(int i=0; i&lt;list_size; i++) printf(&quot;%04d\n&quot;, list[i]);
      
      // WE WANT TO INSERT A NUMBER AT A GIVEN POSITION (IN THIS CASE WE HAVE A POINTER TO THE ITEM)
      int *p = &amp;list[3];
      
      // WE WANT TO PUSH FORWARD ALL THE ELEMENTS OF THE ARRAY BEFORE INSERTING THE ELEMENT
      memcpy( p+1, p, (list_size - (p - list))*sizeof(int));
      list_size++;
      
      // INSERT ELEMENT
      *p = -1;
      
      // LIST ITEMS
      printf(&quot;---\n&quot;); for(int i=0; i&lt;list_size; i++) printf(&quot;%04d\n&quot;, list[i]);
      
      return 0;
  }
  </code></pre>
  <p>The output:</p>
  <pre><code>---
  0002
  0004
  0006
  0008
  0010
  ---
  0002
  0004
  0006
  -001
  0008
  0010
  </code></pre>