Memory jumping

I have a simple script in Arduino and I am trying to make as compact and fast, but once I try to print out the buffer, the memory goes from 9% to 61%.

I am not sure how this can be possible, this only happens as soon as I copy a BYTE from the struct into the buffer and it jumps up.

Is there something in the compiling issue? Am I doing something wrong that I can keep the memory usage to minimal?

So the whole issue happens in the function send_message

typedef struct {
   byte s1;
   byte s2;
   byte id;
   byte length;
   byte message[50];
} message;
message queue[20];

int index_next = 0;

void setup() {
   Serial.begin(9600);
}

void loop() {
next_queue();
}


void send_message(message &msg) {
  byte buff[msg.length+4];
   buff[0] = msg.s1;
   buff[1] = msg.s2;
   buff[2] = msg.id;
   buff[3] = msg.length;
   buff[4] = msg.message[0];
   buff[5] = msg.message[1];
   Serial.write(buff, msg.length+4);
}

void next_queue() {
    if (index_next < 20) { 
        send_message(queue[index_next]);
        index_next++;
    }
}

Before you add the print, the compiler can tell that you do not use anything from the queue array, so it is removed entirely in the optimization phase of compilation. That array needs 1080 bytes of storage.

if you comment out 'Serial.write(buff, msg.length+4);', the memory usage drops back to 9%....

HINT: 'Serial' is a Class/Object

sherzaad:
if you comment out 'Serial.write(buff, msg.length+4);', the memory usage drops back to 9%....

HINT: 'Serial' is a Class/Object

Ok sure, but if I keep the Serial.write and I make the buffer like:

byte buff[10];
buff[0] = 0x10;
buff[1] =0x0A;
....

The memory stay at 9%

Why is increasing when I do buff[0] = msg.s1? I am just adding a BYTE to another BYTE

max246:
Ok sure, but if I keep the Serial.write and I make the buffer like:

byte buff[10];
buff[0] = 0x10;
buff[1] =0x0A;

The memory stay at 9%

Why is increasing when I do buff[0] = msg.s1? I am just adding a BYTE to another BYTE

The compiler is not seeing any reason to create the queue array when you assign constants to buff, so never allocates space for it. The queue array will need 1080 bytes of storage, no way around that when it is actually needed by the code, and that is over 50% of the available memory on an Uno, Nano, etc.

Add the keyword volatile to the declaration of queue and see what that does to memory usage. That will force the compiler to always allocate memory for the array.

You wrote: "I have a simple script in Arduino and I am trying to make as compact and fast, ".

Are you referring to your source code or to the compiled code loaded into the Arduino memory?

In the real world compact and fast cannot both exist in the same program.

Paul