title: How can malloc() cause a SIGSEGV?
body: <p>I have an odd bug in my program, it appears to me that malloc() is causing a SIGSEGV, which as far as my understanding goes does not make any sense. I am using a library called simclist for dynamic lists.</p>
  
  <p>Here is a struct that is referenced later:</p>
  
  <pre><code>typedef struct {
      int msgid;
      int status;
      void* udata;
      list_t queue;
  } msg_t;
  </code></pre>
  
  <p>And here is the code:</p>
  
  <pre><code>msg_t* msg = (msg_t*) malloc( sizeof( msg_t ) );
  
  msg-&gt;msgid = msgid;
  msg-&gt;status = MSG_STAT_NEW;
  msg-&gt;udata = udata;
  list_init( &amp;msg-&gt;queue );
  </code></pre>
  
  <p><code>list_init</code> is where the program fails, here is the code for list_init:</p>
  
  <pre><code>/* list initialization */
  int list_init(list_t *restrict l) {
      if (l == NULL) return -1;
  
      srandom((unsigned long)time(NULL));
  
      l-&gt;numels = 0;
  
      /* head/tail sentinels and mid pointer */
      l-&gt;head_sentinel = (struct list_entry_s *)malloc(sizeof(struct list_entry_s));
      l-&gt;tail_sentinel = (struct list_entry_s *)malloc(sizeof(struct list_entry_s));
      l-&gt;head_sentinel-&gt;next = l-&gt;tail_sentinel;
      l-&gt;tail_sentinel-&gt;prev = l-&gt;head_sentinel;
      l-&gt;head_sentinel-&gt;prev = l-&gt;tail_sentinel-&gt;next = l-&gt;mid = NULL;
      l-&gt;head_sentinel-&gt;data = l-&gt;tail_sentinel-&gt;data = NULL;
  
      /* iteration attributes */
      l-&gt;iter_active = 0;
      l-&gt;iter_pos = 0;
      l-&gt;iter_curentry = NULL;
  
      /* free-list attributes */
      l-&gt;spareels = (struct list_entry_s **)malloc(SIMCLIST_MAX_SPARE_ELEMS * sizeof(struct list_entry_s *));
      l-&gt;spareelsnum = 0;
  
  #ifdef SIMCLIST_WITH_THREADS
      l-&gt;threadcount = 0;
  #endif
  
      list_attributes_setdefaults(l);
  
      assert(list_repOk(l));
      assert(list_attrOk(l));
  
      return 0;
  }
  </code></pre>
  
  <p>the line <code>l-&gt;spareels = (struct list_entry_s **)malloc(SIMCLIST_MAX_SPARE_ELEMS *</code> is where the SIGSEGV is caused according to the stack trace. I am using gdb/nemiver for debugging but am at a loss. The first time this function is called it works fine but it always fails the second time. How can malloc() cause a SIGSEGV?</p>
  
  <p>This is the stack trace:</p>
  
  <pre><code>#0  ?? () at :0
  #1  malloc () at :0
  #2  list_init (l=0x104f290) at src/simclist.c:205
  #3  msg_new (msg_switch=0x1050dc0, msgid=8, udata=0x0) at src/msg_switch.c:218
  #4  exread (sockfd=8, conn_info=0x104e0e0) at src/zimr-proxy/main.c:504
  #5  zfd_select (tv_sec=0) at src/zfildes.c:124
  #6  main (argc=3, argv=0x7fffcabe44f8) at src/zimr-proxy/main.c:210
  </code></pre>
  
  <p>Any help or insight is very appreciated!</p>