Skip to content

FreeRam.ino example "p = new byte[3000]" failure does not show free RAM can change #6

Open
@philj404

Description

@philj404

This is for an Arduino Uno, which has only 2048 bytes RAM available.

The problem is really in examples/FreeRam/FreeRam.ino, but its output is harder to interpret.

The actual issue is on FreeRam.ino line 21:

    ...
   byte *p = new byte[3000];    
    ...

Since there is only 2k RAM available this allocation will fail on an Uno. On failure, nothing gets allocated on the heap, and the heap size does not change. This is not not so interesting for an example.

I found a smaller array size made FreeRam.ino more interesting:

    ...
   byte *p = new byte[300];    
    ...

See #4 for a pull request to make this allocation request successful.

For a more direct demonstration the heap growing and shrinking, I wrote GetMemorySize.ino:

#include <MemoryUsage.h>

// Simple example to report memory sizes

void reportAllocation(int numBytes) {

    Serial.print(F("Allocating for "));
    Serial.print( numBytes );
    Serial.print(F(" bytes; "));
    
    byte *p = new byte[numBytes];

    if (p) {
        Serial.println(F("...success."));
    } else {
        Serial.println(F("...allocation FAILED"));
    }

    MEMORY_PRINT_HEAPSIZE
    FREERAM_PRINT

    Serial.println(F("\ndeleting byte array with delete"));
    delete p;   // don't want a memory leak!
    p = 0;      // don't want a dangling/obsolete pointer

    MEMORY_PRINT_HEAPSIZE
    FREERAM_PRINT
}

void setup() {
    Serial.begin(115200);
    delay(1000);
    Serial.println(F( "Running " __FILE__ ", Built " __DATE__));

    Serial.println(F("\nStarting conditions"));
    MEMORY_PRINT_TOTALSIZE
    MEMORY_PRINT_HEAPSIZE
    FREERAM_PRINT

    Serial.println(F("\nallocate a byte array with new; too big to fit in RAM?"));
    reportAllocation(3000);

    Serial.println(F("\nallocate smaller byte array with new (it should fit)"));
    reportAllocation(300);

    Serial.println(F("\nFinal conditions"));
    MEMORY_PRINT_HEAPSIZE
    FREERAM_PRINT
}

void loop() {
    // User reads output from setup().
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions