title: malloc behaviour on an embedded system
body: <p>I'm currently working on an embedded project (STM32F103RB, CooCox CoIDE v.1.7.6 with arm-none-eabi-gcc 4.8 2013q4) and I'm trying to understand how <code>malloc()</code> behaves on plain <code>C</code> when the RAM is full.</p>
  
  <p>My STM32 has 20kB = 0x5000Bytes of RAM, 0x200 are used for the stack.</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include "stm32f10x.h"
  
  struct list_el {
     char weight[1024];
  };
  
  typedef struct list_el item;
  
  int main(void)
  {
      item * curr;
  
      // allocate until RAM is full
      do {
          curr = (item *)malloc(sizeof(item));
      } while (curr != NULL);
  
      // I know, free() is missing. Program is supposed to crash
  
      return 0;
  }
  </code></pre>
  
  <p>I would expect <code>malloc()</code> to return <code>NULL</code> as soon as the heap is too small for allocating:</p>
  
  <p><code>0x5000</code> (RAM) - <code>0x83C</code> (bss) - <code>0x200</code> (stack) = <code>0x45C4</code> (heap)</p>
  
  <p>So when executing the <code>malloc()</code> for the 18th time. One item is 1024=<code>0x400</code> Bytes large.</p>
  
  <p>But instead the uC calls the <code>HardFault_Handler(void)</code> after the 18th time (not even the <code>MemManager_Handler(void)</code>)</p>
  
  <p>Does anybody have an advice how to forecast a <code>malloc()</code> failure - since waiting for a <code>NULL</code> return doesn't seem to work.</p>
  
  <p>Thank you. </p>