4

After experiencing failures of my Arduino projects due to low memory, I decided to do some research into it so I could understand better where the problems were. I eventually came to this code:

void setup() {
  pinMode(13, OUTPUT);

  int len = 5000;
  byte *data = (byte *)malloc(len * sizeof(*data));
}

void loop() {
  int timing = 1000;
  delay(timing);
  digitalWrite(13, HIGH);
  delay(timing);
  digitalWrite(13, LOW);
}

I expected that since my Arduino Uno does not have enough RAM to hold an array of 5000 bytes (Atmel's information on the Atmega328P shows us it only has 2KB of SRAM), the code in void loop() would not be able to run due to lack of memory. As far as my understanding goes, once malloc has allocated 5000 bytes (or as many as it could of the 5000 bytes), there would physically not be enough space left in memory for the variable timing and the LED I attached on pin 13 would not flash on and off at intervals of 1 second.

However, my LED toggles at perfect intervals of 1 second. Why would this occur? Isn't memory allocated by malloc unavailable for use by anything else until free is called on it?

1 Answer 1

7

If you add a debugging print you will see what is happening:

void setup() {
  Serial.begin (115200);
  Serial.println ();

  pinMode(13, OUTPUT);

  int len = 5000;
  byte *data = (byte *)malloc(len * sizeof(*data));

  Serial.print ("data = ");
  Serial.println ((int) data);
}

Output:

data = 0

The malloc failed, it returned NULL, the rest of the program proceeded normally.


once malloc has allocated 5000 bytes (or as many as it could of the 5000 bytes)

malloc does not return with a partial allocation. It either allocates the amount you requested or none at all.

1
  • I guess error checking is very important and handy, thank you.
    – user3933
    Aug 1, 2015 at 7:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.