Simple RAM alloc test - STACK vs HEAP

Post your cool example code here.
Post Reply
User avatar
Pito
Posts: 1625
Joined: Sat Mar 26, 2016 3:26 pm
Location: Rapa Nui

Simple RAM alloc test - STACK vs HEAP

Post by Pito » Thu Aug 31, 2017 9:52 am

A simple test to play with 2 buffers which could be allocated on the Stack and/or in the Heap.
Adjust the buffers sizes such the buffers fit into your chip.

Code: Select all

// SMALL TEST OF RAM ALLOCATION - STACK vs. HEAP
// Pito 8/2017
// Provided as-is, no warranties of any kind are provided

#include "Arduino.h"

// BUFFER1
#define bufsize1 34*1024
#define cb1 0x77
// BUFFER2
#define bufsize2 17*1024
#define cb2 0xad
// Checksums
uint32_t i, sum1, sum2;

void setup() {

  Serial.begin(115200);
  delay(4000);  // Wait on USB
  sum1 = 0;
  sum2 = 0;

  Serial.println("Starting the RAM ALLOC test..");

  // UNCOMMENT to Allocate on STACK
  //  uint8_t buf1[bufsize1];
  //  uint8_t buf2[bufsize2];
  //

  // UNCOMMENT to Allocate in HEAP
  uint8_t* buf1 = (uint8_t*) malloc(bufsize1 * sizeof(uint8_t));
  if (buf1 == NULL) {
    Serial.println("      ############### BUF1 MALLOC FAILED..");
  }
  uint8_t* buf2 = (uint8_t*) malloc(bufsize2 * sizeof(uint8_t));
  if (buf2 == NULL) {
    Serial.println("      ############### BUF2 MALLOC FAILED..");
  }
  //

// fill in the buffers with data
  for (i = 0; i < bufsize1; i++) {
    buf1[i] = cb1;
    sum1 = sum1 + buf1[i];
  }
  for (i = 0; i < bufsize2; i++) {
    buf2[i] = cb2;
    sum2 = sum2 + buf2[i];
  }

  if (sum1 == (bufsize1 * cb1)) {
    Serial.println("Buf1 OK..");
  } else {
    Serial.println("Buf1 ERROR..");
  }
  if (sum2 == (bufsize2 * cb2)) {
    Serial.println("Buf2 OK..");
  } else {
    Serial.println("Buf2 ERROR..");
  }
   // COMMENT OUT with buffers in STACK
   free(buf1);
   free(buf2);
}

void loop() {
}
Under Sloeber, Blue F103ZE, Libmaple F1 latest with -u fix in platform.txt, 34kB and 17kB buffers in the Heap.

Code: Select all

Starting the RAM ALLOC test..
Buf1 OK..
Buf2 OK..
Pukao Hats Cleaning Services Ltd.

Post Reply