title: Error while accessing element of array in struct
body: <p>I'm trying to write an "ArrayList" program (Similar to the Java <a href="https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html" rel="nofollow"><code>ArrayList</code></a>) that will expand automaticly using <a href="http://www.tutorialspoint.com/c_standard_library/c_function_realloc.htm" rel="nofollow"><code>realloc</code></a>, so that the programmer won't have to worry about storage space in arrays. This is my code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;errno.h&gt;
  
  #define ARR_DEFAULT_SIZE 20
  #define INCR 10
  
  #define ARRTYPE char // Files using this #undef this macro and provide their own type
  
  typedef struct {
      ARRTYPE *arr;
      long size;
      long nextincr;
  } arrlst;
  
  arrlst *nlst(void);
  void add(arrlst *, ARRTYPE);
  ARRTYPE elmat(arrlst *, long);
  
  int main(int argc, char **argv) {
      arrlst *lst = nlst();
      add(lst, 'h');
  }
  
  arrlst *nlst() {
      arrlst lst = { malloc(ARR_DEFAULT_SIZE), 0, ARR_DEFAULT_SIZE };
      arrlst *lstptr = &amp;lst;
      return lstptr;
  }
  
  void add(arrlst *lst, ARRTYPE elm) {
      if (lst-&gt;size &gt;= lst-&gt;nextincr) {
          ARRTYPE *tmp = lst-&gt;arr;
          lst-&gt;nextincr += INCR;
          lst-&gt;arr = realloc(lst-&gt;arr, lst-&gt;nextincr);
  
          for (int i = 0; i &lt; sizeof tmp; i++)
              lst-&gt;arr[i] = tmp[i];
      }
  
      lst-&gt;arr[lst-&gt;size++] = elm;
  }
  
  ARRTYPE elmat(arrlst *lst, long at) {
      if (lst-&gt;size &lt; at)
          strerror(14);
  
      return lst-&gt;arr[at];
  }
  </code></pre>
  
  <p>My problem is that whenever I run this, calling <code>add()</code> produces a segfault, and since most of the code in <code>add()</code> is skipped on the first time calling it, the line of error must be:</p>
  
  <pre><code>lst-&gt;arr[lst-&gt;size++] = elm;
  </code></pre>
  
  <p>And I don't know why this would segfault. Please help!</p>