title: Malloc cannot allocate memory for a structure
body: <p>I have the <code>Segmentation fault (core dumped)</code> error.</p>
  
  <p><strong>main.c</strong></p>
  
  <pre><code>#include "header1.h"
  
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  
  int main(int argc, char** argv) {
          struct t_list *list = NULL;
          doFill(list);
          printf("%s\n", list-&gt;name);
          free(list);
          return 0;
  }
  </code></pre>
  
  <p><strong>header1.h</strong></p>
  
  <pre><code>#ifndef HEADER1_H
  #define HEADER1_H
  
  struct t_list {
    char *name;
    struct t_list *next;
  };
  
  void doFill(struct t_list *list);
  
  #endif
  </code></pre>
  
  <p><strong>worker.c</strong></p>
  
  <pre><code>#include "header1.h"
  #include &lt;stdlib.h&gt;
  
  void doFill(struct t_list *list) {
      list = (struct t_list *) malloc(sizeof(struct t_list));
      char *tmp = "somename";
      list-&gt;name = tmp;
      list-&gt;next = NULL;
  }
  </code></pre>
  
  <p>When I run this (<code>gcc -g main.c worker.c -o test</code>) I get (on the line with <code>printf</code> in main.c):</p>
  
  <pre><code>Segmentation fault (core dumped)
  </code></pre>
  
  <p>In <code>gdb</code> I see:</p>
  
  <pre><code>Temporary breakpoint 1, main (argc=1, argv=0x7fffffffddf8) at main.c:8
  8       struct t_list *list = NULL;
  (gdb) next
  9       doFill(list);
  (gdb) step
  doFill (list=0x0) at worker.c:6
  6       list = (struct t_list *) malloc(sizeof(struct t_list));
  (gdb) p list
  $1 = (struct t_list *) 0x0
  (gdb) next
  7       char *tmp = "somename";
  (gdb) p list
  $2 = (struct t_list *) 0x0
  </code></pre>
  
  <p>As you can see <code>malloc</code> in worker.c doesn't allocate memory for the <code>list</code> variable (the pointer before and after <code>malloc</code> points at <code>0x0</code>).</p>
  
  <p>If I move the code from the <code>doFill</code> procedure in main.c it works correctly:</p>
  
  <p><strong>main.c</strong></p>
  
  <pre><code>#include "header1.h"
  
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  
  int main(int argc, char** argv) {
      struct t_list *list;
      list = (struct t_list *) malloc(sizeof(struct t_list));
      char *tmp = "somename";
      list-&gt;name = tmp;
      list-&gt;next = NULL;
      printf("%s\n", list-&gt;name);
      free(list);
      return 0;
  }
  
  $ gcc -g main.c -o test
  $ ./test
  somename
  </code></pre>
  
  <p>How is it possible? What do I do wrong?</p>
  
  <pre><code>gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1)
  </code></pre>