title: recoding malloc with mmap strange segfault
body: <p>I am actually recoding malloc using mmap function, the problem is i am getting a segfault largely before the end of the allocated memory.
  I can't find where is the problem in my code.</p>
  
  <p>The init() function is called at the first call of my malloc, then the search_for_free_space() is called instead.</p>
  
  <p>I am allocating 409600 bytes with mmap (100 pages), but the code is getting segfault after using only 26000 bytes without reason.</p>
  
  <p>When i'm multiplying the size of my mmap by 10 the segfault appears later, but i verified that the size given to my mmap is well 409600 and not less.</p>
  
  <p>The segfault should appear only after using all memory as i have not done the next part of the code but it appear too early.</p>
  
  <p>code (you can run it):</p>
  
  <pre><code>#include &lt;sys/mman.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdio.h&gt;
  
  # define PAGE_SIZE getpagesize()
  
  typedef struct  s_zone
  {
      int             size;
      int             free;
      struct s_zone   *next;
  }               t_zone;
  
  typedef struct  s_e
  {
      t_zone  *tiny;
  }               t_e;
  
  static t_e  g_e;
  
  void    *allocate(size_t size)
  {
      printf("%s", "allocated memory: ");
      printf("%d\n", (int)size);
      return (mmap(NULL, size, PROT_READ | PROT_WRITE,
          MAP_PRIVATE | MAP_ANON, -1, 0));
  }
  
  void    *init_tiny(size_t size)
  {
      g_e.tiny = (t_zone*)allocate((PAGE_SIZE * 100));
      g_e.tiny-&gt;size = size;
      g_e.tiny-&gt;free = 0;
      g_e.tiny-&gt;next = g_e.tiny + sizeof(t_zone) + size;
      g_e.tiny-&gt;next-&gt;size = PAGE_SIZE;
      g_e.tiny-&gt;next-&gt;free = 1;
      g_e.tiny-&gt;next-&gt;next = NULL;
      return (g_e.tiny + sizeof(t_zone));
  }
  
  void    *search_for_free_space(size_t size, t_zone *zone)
  {
      size_t  i;
  
      while (zone-&gt;free != 1 || zone-&gt;size &lt; size)
          zone = zone-&gt;next;
      zone-&gt;free = 0;
      zone-&gt;size = size;
      zone-&gt;next = zone + sizeof(t_zone) + size;
      zone-&gt;next-&gt;size = PAGE_SIZE;
      zone-&gt;next-&gt;free = 1;
      zone-&gt;next-&gt;next = NULL;
      return (zone + sizeof(t_zone));
  }
  
  void    *malloc2(size_t size)
  {
      if (g_e.tiny == NULL)
          return (init_tiny(size));
      else
          return (search_for_free_space(size, g_e.tiny));
      return (NULL);
  }
  
  int     main(void)
  {
      int     i;
  
      i = 0;
      while (i &lt; 300)
      {
          malloc2(2000);
          i++;
          printf("%s", "used memory: ");
          printf("%d\n", (int)((2000 * i) + (i * sizeof(t_zone))));
      }
      return (0);
  }
  </code></pre>