Home > Enterprise >  Why a pointer to a class take less memory SRAM than a "classic" variable
Why a pointer to a class take less memory SRAM than a "classic" variable

Time:10-07

i have a Arduino Micro with 3 time of flight LIDAR micro sensors welded to it. In my code i was creating 3 Global variable like this:

Adafruit_VL53L0X lox0 = Adafruit_VL53L0X();
Adafruit_VL53L0X lox1 = Adafruit_VL53L0X();
Adafruit_VL53L0X lox2 = Adafruit_VL53L0X();

And it took like ~80% of the memory Now i am creating my objects like this

Adafruit_VL53L0X *lox_array[3] = {new Adafruit_VL53L0X(), new Adafruit_VL53L0X(), new Adafruit_VL53L0X()};

And it take 30% of my entire program

I Try to look on arduino documentation but i don't find anything that can help me. I can understand that creating a "classic" object can fill the memory. But where is the memory zone located when the pointer is create ?

CodePudding user response:

You use the same amount of memory either way. (Actually, the second way uses a tiny bit more, because the pointers need to be stored as well.)

It's just that with the first way, the memory is already allocated statically from the start and part of the data size of your program, so your compiler can tell you about it, while with the second way, the memory is allocated at runtime dynamically, so your compiler doesn't know about it up front.

I dare say that the second method is more dangerous, because consider the following scenario: Let's assume your other code and data already uses 90% of the memory at compile-time. If you use your first method, you will fail to upload the program because it would now use something like 150%, so you already know it won't work. But if you use your second method, your program will compile and upload just fine, but then crash when trying to allocate the extra memory at runtime.

(By the way, the compiler message is a bit incomplete. It should rather say "leaving 1750 bytes for local variables and dynamically allocated objects" or something along those lines).

enter image description here

  • Related