Array not stoping at declared size

I´m trying out a code just to better understand arrays and serial comunication.

I´m declaring a char array with 4 positions, but when i test it i can insert up to 12 characters before it stops working.

I would like to understand what i am missing.

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  char c[4];
  char t;
  int n;
  if(Serial.available()>0){
    t = Serial.read();
    n=0;
    while(t != '\r'){
      c[n] = t;
      n++;
      t=Serial.read();
    }
    c[n]='\0';
    n=0;
  Serial.println(c);
  }
  Serial.println('x');
  delay(1000);
  
}

Welcome to C/C++!

You're missing an understanding of arrays.

It's up to you to keep track of how much memory you are using

2 Likes

You are missing nothing. It is purely a matter of chance and luck…

You can, as you see, write or read beyond the end of the array. But it means you may be reading garbage, or writing over things you really ought not to.

Welcome to C/C++. Gives you the tools to shoot yourself in the foot.

So be careful. Sometimes it makes sense to add code to ensure that you are not writing or reading out of bounds.

a7

1 Like

As many as that ?

Sometimes writing just one byte beyond the end of the array is enough to crash a program.

1 Like

... cocks the gun and takes off the safety.
Aiming (or not) and firing is your responsibility.

1 Like

You are checking to see if there is at least one byte available from the serial. Then you read the byte. Then you enter a while loop to read bytes from the serial without checking to see if any more are available!!! Serial.read() returns -1 if there is not data available. At 9600 bps you are only going to get 1 byte per millisecond. Since you are not checking for the end of the array you are corrupting a whole lot of memory in 1 millisecond.

Thank you ill keep an eye out for that in the future.
But i haven´t had this issue, not sure if the loop overhead gave it enough time or if they made the read method safer.

Nothing in your code prevents n from being 4 or more.

What would you expect to stop it?

Nobody has made ANYTHING "safer". If you have not had problems doing this in the past, then you've been incredibly lucky. It WILL NOT WORK RELIABLY. EVER.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.