6 years ago.

Operator new out of memory // causes crash - Nucleo-L476RG


#include "mbed.h"
 
 
Serial pc(USBTX, USBRX);

void fail()
{
    pc.printf("Caught the failure\r\n");    
}
 
 
class Test
{
    public:
        unsigned char woot[100];
};
 
 
int main() {
    pc.baud(115200);
    Test *dummy;
    int index = 0;
    
    while(1) {
        dummy = new Test;
        if (dummy == NULL) fail();
        pc.printf("%u %i\n", index++, sizeof(*dummy));
    }
} 

Running the above code( which I found on the mbed forum) causes the mbed to fail with the following text

...

837 100

838 100

839 100

840 100

841 100

842 100

843 100

844 100

++ MbedOS Error Info ++ Error Status: 0x8001011F Code: 287 Module: 1 Error Message: Operator new out of memory

Location: 0x8005DB7 Error Value: 0x64 Current Thread: Id: 0x20001F08 Entry: 0x80071C1 StackSize: 0x1000 StackMem: 0x20000F08 SP: 0x20001EC0

For more info, visit: https://armmbed.github.io/mbedos-error/?error=0x8001011F

Looking at the amount of memory used is simple 844x100= 84K. While this module (or the MCU) has 128K of Memory. Why do it crashes? why a new operator should crash at all? Shouldn't just return NULL pointer?

2 Answers

6 years ago.

What is your point?

84K + stack + overhead + USB buffers + serial object sounds like close to 128K to me. You can look at the map file to find the real overhead.

better code would be to place the dummy = new Test in to a try catch block.

perhaps operator new should not throw an exception, but do you actually want to ship release code to customers that silently fails?

6 years ago.

If you don't want new to crash, you can use std::nothrow with new.

in your case:

dummy = new (std::nothrow) Test;

With std::nothrow return value will be NULL if new fails.