title: Valgrind error and generic list with one allocation per element
body: <p>I'm experimenting with linked lists and tried to create a generic doubly linked list which allocates memory only once for each node. It means that the memory for the node and the element the node contains is allocated within same <code>malloc</code> invocation.
  The list itself is a structure which contains size of a unit (initialized with <code>sizeof(struct which_is_an_element)</code>:</p>
  
  <pre><code>struct doubly_linked_list
  {
      struct dll_node *head, *tail;
      size_t elem_size;
  };
  </code></pre>
  
  <p>The node:</p>
  
  <pre><code>struct dll_node
  {
      struct dll_node *next, *prev;
      void *elem;
  };
  </code></pre>
  
  <p>Now, when I try to insert element and initialize it:</p>
  
  <pre><code>static struct dll_node * new_node(
          struct doubly_linked_list *l, 
          void *elem)
  {
      struct dll_node *n = malloc (
          sizeof(struct dll_node) + l-&gt;elem_size);
  
      // This line throws valgrind error
      memcpy(n + sizeof(struct dll_node), elem, l-&gt;elem_size); 
  
      n-&gt;prev = n-&gt;next = NULL;
      n-&gt;elem = n + sizeof(struct dll_node);
      return n;
  }
  </code></pre>
  
  <p>I get a valgrind error:</p>
  
  <blockquote>
    <p>Invalid write of size 8<br>
    at 0x4C3217B: memcpy@@GLIBC_2.14   (vg_replace_strmem.c:1022)
    by 0x400705: new_node (doubly_linked_list.c:20)<br>
    by 0x400768: dl_list_insert_at_tail   (doubly_linked_list.c:30)<br>
    by 0x40093F: main (main.c:24)<br>
    Address 0x5204280 is 480 bytes inside an unallocated block of size 4,194,112 in arena "client"  </p>
  </blockquote>
  
  <ol>
  <li>Does really <code>memcpy</code> write inside unallocated block as the size of the allocated memory is equal to <code>sizeof(struct which_is_an_element) + sizeof(dll_node)</code>?</li>
  <li>Are those issues caused by valgrind thinking the allocated memory has size = <code>sizeof(struct dll_node)</code> because of the type of the pointer called <code>n</code> inside <code>new_node</code> function which points to the data?</li>
  <li>Is this approach good? Can I allocate the memory once for each element or should I allocate memory for the node and the element separately?</li>
  <li>If this approach is good then how could I get rid of this valgrind error?</li>
  </ol>