简体   繁体   中英

c++ Buffer overflow or corrupted variables

Can this code cause a buffer overflow when unexpected messages are delivered? Also the expected messages are simple "1" and "-1".

char rcv[64] {};
  int i = 0;
  while (modem.available()) {
    rcv[i++] = (char)modem.read();
  }
  String data_received = rcv;
  if (data_received == "") {
    Serial.println("Null");
  } else {
    correction_var = data_received.toInt();
  }

Since my arduino's RTC suddenly started acting strange and I can't find a proper reason for this, except that before he went nuts apparently a message failed to be sent to the Arduino. This bit of code right here handles messages received so maybe something went outside of what it should have and messed with the RTC's alarm variables?

Update: So none of this was NOT a buffer overflow problem, the Ardunino's RTC apparently has some sort of problem since even after resetting the code, the problem persists, this time from the beginning, and such I decided to create a new thread Here .

You are simply reading an unlimited amount of values without checking if your buffer is full. From your code:

char rcv[64] {};
int i = 0;
while (modem.available()) {
    rcv[i++] = (char)modem.read();
}

It's quite obvious your char-array rcv will overflow after receiving 64 chars. Maybe you should stop reading once your receive-buffer is full?

char rcv[64] {};
int i = 0;
while (modem.available() && i < 64) {
    rcv[i++] = (char)modem.read();
}

Or you could overwrite the oldest value after reading new ones.

char rcv[64] {};
int i = 0;
while (modem.available()) {
    rcv[i % 64] = (char)modem.read();
    ++i;
}

If modem.available() returns true when i reaches 64, then you will have a buffer overflow.

Additionally, String data_received = rcv; may look for a null terminator (I don't know how String is implemented) in rcv, which may not be there and cause String to read past the end of the rcv buffer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM