title: Segmentation fault when copying a portion of an array in c
body: <p>I have a function here that copies a portion of an array (first to last) to a new array.  When I ran the code, I ended up getting seg fault.  I know that seg faults happen when I don't allocate enough space to the array or when I try to access memory that hasn't been allocated.  But for my len, I already set it as last-first+1 which should be enough to encompass the portion of the array that I want to copy.  But why does it still give me seg fault? Or am I missing something?</p>
  
  <p>Here is the struct for my code I've done:</p>
  
  <pre><code>typedef struct {
    int* data;
    unsigned int len;
  } intarr_t;
  </code></pre>
  
  <p>Here's the function to copy the portion of the array to a new one:</p>
  
  <pre><code>intarr_t* intarr_copy_subarray( intarr_t* ia, 
                  unsigned int first, 
                  unsigned int last )
  {
      unsigned int len = last-first+1;
      intarr_t* newia = malloc(sizeof(intarr_t));
      assert (newia);
      newia-&gt;data = malloc(sizeof(int)*len);
      assert (newia-&gt;data);
      newia-&gt;len = len;
      if (newia == 0 || ia == NULL || last &lt; first)
      { 
          return NULL;
      }
      else
      {
          for (int x = first; x &lt;= last; x++)
          {
              memcpy (newia-&gt;data[x], ia-&gt;data[x], (len*sizeof(int)));
          }
          return newia;
      }
      free (newia);
      return 0;
  }
  </code></pre>