AnsweredAssumed Answered

BUG: malloc overruns heap, returns invalid pointer, and corrupts memory

Question asked by Dave Nadler on Dec 28, 2016
Latest reply on Nov 2, 2017 by Dave Nadler

A simple example (created by pruning down an NXP blinky example) shows malloc over-running heap and returning an invalid pointer. Obviously this corrupts memory in any non-trivial program.
KDS 3.2, Freedom K64F board.
Two bugs are illustrated:

  1. malloc is supposed to return NULL when no memory is available.
    Please see:
    For embedded applications, a trap on out-of-memory would be better!
    In no case is returning a pointer outside the heap acceptable.
  2. As shown in this example, the default heap size of 1kB (for a processor with 256kB RAM!)
    in K64F example is too small for even a trivial RTL use, even before the application tries to use malloc.
    NXP examples should set sensible default heap size!

Here's the relevant test code (complete project is attached):

// Quick-and-Dirty Blinky7 example for Freedom K64F
// Shows malloc memory over-run and return of invalid (non-NULL) pointer

#include <stdint.h>
// Debug only:
#include <stdio.h> // printf
#include <stdlib.h> // malloc
extern uint32_t __HeapBase;
extern uint32_t __HeapLimit;
// ....
int main(void)
    printf("Hello there; this tests semi-hosting (and printf internally calls _malloc_r, and over-runs heap)\n");
    void* pHeapBase = ((void*)&__HeapBase);
    void* pHeapLimit= ((void*)&__HeapLimit);
    void* pMalloc = malloc(16); // does malloc return something within expected heap area? Ooops: 0x200005c0
    printf("Heap: base 0x%x, limit 0x%x, very first malloc 0x%x\n",pHeapBase, pHeapLimit, pMalloc);
    // Prints: Heap: base 0x20000000, limit 0x20000400, very first malloc 0x200005c0
    assert (pMalloc>=pHeapBase && pMalloc<pHeapLimit);

Original Attachment has been moved to: