Bill Greiman
Well-known member
malloc() crashes long before the heap is exhausted. The problem is that this version of newlib uses a 4096 byte page size.
This sketch crashes with a hard fault exception with over 4096 bytes of unallocated heap space:
The output is:
malloc() now return null but about 4k is not allocated.
This sketch crashes with a hard fault exception with over 4096 bytes of unallocated heap space:
Code:
#include <unistd.h>
extern long _estack;
void setup() {
Serial.begin(9600);
while (!Serial) {}
delay(2000);
Serial.print("&_estack: ");
Serial.println((int)&_estack, HEX);
for (int i = 0; ;i++) {
Serial.print("sbrk: ");
Serial.println((int)sbrk(0), HEX);
Serial.println("calling malloc");
Serial.flush();
char* p = (char*)malloc(1000);
Serial.print("malloc returned: ");
Serial.println((int)p, HEX);
Serial.flush();
if (!p) break;
}
}
void loop() {}
The following change to _sbrk softens the failure:&_estack: 20002000
sbrk: 1FFFF13C
calling malloc
malloc returned: 1FFFF148
sbrk: 20000000
calling malloc
malloc returned: 1FFFF538
sbrk: 20000000
calling malloc
malloc returned: 1FFFF928
sbrk: 20000000
calling malloc
malloc returned: 1FFFFD18
sbrk: 20001000
calling malloc
malloc returned: 20000108
sbrk: 20001000
calling malloc
malloc returned: 200004F8
sbrk: 20001000
calling malloc
malloc returned: 200008E8
sbrk: 20001000
calling malloc
Code:
void * _sbrk(int incr)
{
static char *heap_end = (char *)&_ebss;
char *prev = heap_end;
/* added by Bill Greiman */
if ((heap_end + incr) >= &_estack) return -1;
heap_end += incr;
return prev;
}
&_estack: 20002000
sbrk: 1FFFF0A0
calling malloc
malloc returned: 1FFFF0A8
sbrk: 20000000
calling malloc
malloc returned: 1FFFF498
sbrk: 20000000
calling malloc
malloc returned: 1FFFF888
sbrk: 20000000
calling malloc
malloc returned: 1FFFFC78
sbrk: 20001000
calling malloc
malloc returned: 20000068
sbrk: 20001000
calling malloc
malloc returned: 20000458
sbrk: 20001000
calling malloc
malloc returned: 20000848
sbrk: 20001000
calling malloc
malloc returned: 0
Last edited: