title: malloc() in newlib : does it waste memory after one big failure allocation?
body: <p>I am writing an embedded software for STM32F7 and my libc is newlib-2.4.0.20160527.</p>
  
  <p>I have implemented <code>_sbrk()</code> as follows:</p>
  
  <pre><code>extern intptr_t g_bss_end; /* value after the last byte in .bss */
  extern intptr_t g_msp_lim; /* stack buffer starts at this address */
  
  intptr_t _sbrk(ptrdiff_t heap_incr)
  {
      static intptr_t heap_end = 0;
  
      intptr_t prev_heap_end;
      intptr_t new_heap_end;
  
      if(heap_end == 0) {
          heap_end = (intptr_t)&amp;g_bss_end;
      }
  
      prev_heap_end = heap_end;
      new_heap_end = prev_heap_end + heap_incr;
  
      if(new_heap_end &gt;= g_msp_lim) {
          errno = ENOMEM;
  
          return -1;
      }
  
      heap_end = new_heap_end;
  
      return prev_heap_end;
  }
  </code></pre>
  
  <p>Then, when I do the following:</p>
  
  <pre><code>/* total capacity of my heap is 0x40000 */
  void * mem = malloc(0x40000);
  free(mem); mem = 0;
  mem = malloc(0x40000);
  </code></pre>
  
  <p>everything works fine (i.e., malloc returns non-zero twice).</p>
  
  <p>But when I do the following (for testing purposes):</p>
  
  <pre><code>for(int32_t sz = 0x50000; sz &gt;= 0; sz--) {
      void * mem = malloc(sz);
  
      if(mem != 0) {
          __BKPT();
          free(mem);
  
          break;
      }
  }
  </code></pre>
  
  <p>every <code>malloc()</code> fails, even <code>malloc(0)</code> (i.e., <code>__BKPT()</code> is <strong>never reached</strong>). So, there is no allocated memory on heap in fact (I did not get any <code>mem != 0</code> so I can not even <code>free()</code> something) and there is also no available memory.</p>
  
  <p>I expected <code>malloc()</code> to fail for every <code>sz &gt; 0x40000</code> and succeed for every <code>sz &lt;= 0x40000</code> (assuming <code>free()</code> works fine after each <code>malloc()</code>).</p>
  
  <p>Have I missed something, or this is either a bug or intended behavior in newlib?</p>