0

I have this sketch:

const uint32_t len = 65536;
uint8_t arr[len];

void setup() {}

void loop() {}

The length of the array should fit into the dynamic memory. However, when I compile the sketch it says this in the output window:

Sketch uses 10528 bytes (0%) of program storage space. Maximum is 2031616 bytes.
Global variables use 13504 bytes (1%) of dynamic memory, leaving 1034224 bytes for local variables. Maximum is 1048576 bytes.

If I change len to 10, that doesn't change. The compiler is set to "Debug", so it should not get optimized away. This indicates, that the memory isn't actually being allocated. What seems to be the problem here?

I am compiling for the Teensy 4.0, but the output is the same in essence for the Arduino Uno and other boards (with lower memory sizes).

2
  • How are you compiling it? If you're not actually using the array it may just be optimized away. May 17 at 14:43
  • My guess would be this is due to not putting any data in it. May 17 at 14:44
4

There is no problem here. Only the compiler is a bit smarter than you anticipated. It sees, that you are not using arr anywhere, so it just optimizes it out.

There are two ways to prevent that, if you really want to:

  • I think you can use flags to tell the compiler, that this shouldn't be optimized out. I'm no expert in this, others might know more about this and add their own answer
  • You can just start using it.
4
  • That is a good point, however I had already thought of that. See the updated question.
    – LukasFun
    May 17 at 15:29
  • Nevermind, apparently this setting still leads to the compiler optimizing it away. Once there is a line that writes data to the array, the proper memory usage for global variables gets displayed.
    – LukasFun
    May 17 at 16:02
  • The only thing that remains after this is that malloc() doesn't seem to work this way.
    – LukasFun
    May 17 at 16:07
  • @LukasFun Correct--malloc does precisely what it's supposed to, allocate the memory, at the time it's called. Whether or not that memory is used is irrelevant. May 17 at 17:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.