Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
philj404 opened this issue Jun 4, 2021 · 0 comments

Comments

@philj404
Copy link

philj404 commented Jun 4, 2021

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().
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant