title: snprintf() prints garbage floats with newlib nano
body: <p>I am running a bare metal embedded system with an ARM Cortex-M3 (STM32F205). When I try to use <code>snprintf()</code> with float numbers, e.g.:</p>
  
  <pre><code>float f;
  
  f = 1.23;
  snprintf(s, 20, "%5.2f", f);
  </code></pre>
  
  <p>I get garbage into <code>s</code>. The format seems to be honored, i.e. the garbage is a well-formed string with digits, decimal point, and two trailing digits. However, if I repeat the <code>snprintf</code>, the string may change between two calls.</p>
  
  <p>Floating point mathematics seems to work otherwise, and <code>snprintf</code> works with integers, e.g.:</p>
  
  <pre><code>snprintf(s, 20, "%10d", 1234567);
  </code></pre>
  
  <p>I use the <code>newlib-nano</code> implementation with the <code>-u _printf_float</code> linker switch. The compiler is <code>arm-none-eabi-gcc</code>.</p>
  
  <p>I do have a strong suspicion of memory allocation problems, as integers are printed without any hiccups, but floats act as if they got corrupted in the process. The <code>printf</code> family functions call <code>malloc</code> with floats, not with integers.</p>
  
  <p>The only piece of code not belonging to <code>newlib</code> I am using in this context is my <code>_sbrk()</code>, which is required by <code>malloc</code>.</p>
  
  <pre><code>caddr_t _sbrk(int incr)
  {
    extern char _Heap_Begin; // Defined by the linker.
    extern char _Heap_Limit; // Defined by the linker.
  
    static char* current_heap_end;
    char* current_block_address;
  
    // first allocation
    if (current_heap_end == 0)
        current_heap_end = &amp;_Heap_Begin;
  
    current_block_address = current_heap_end;
  
    // increment and align to 4-octet border
    incr = (incr + 3) &amp; (~3);
    current_heap_end += incr;
  
    // Overflow?
    if (current_heap_end &gt; &amp;_Heap_Limit)
      {
      errno = ENOMEM;
      current_heap_end = current_block_address;
      return (caddr_t) - 1;
      }
  
    return (caddr_t)current_block_address;
  }
  </code></pre>
  
  <p>As far as I have been able to track, this should work. It seems that no-one ever calls it with negative increments, but I guess that is due to the design of the newlib <code>malloc</code>. The only slightly odd thing is that the first call to <code>_sbrk</code> has a zero increment. (But this may be just <code>malloc</code>'s curiosity about the starting address of the heap.)</p>
  
  <p>The stack should not collide with the heap, as there is around 60 KiB RAM for the two. The linker script may be insane, but at least the heap and stack addresses seem to be correct.</p>