This question is similar to this one: Serial.println changes return value of function (Arduino)
I have a function, test(byte _b[])
, which receives a byte array and changes its values using a local temporary byte array. That local byte array is destroyed when function test
returns, so the caller should not be able to access it. However, a Serial.println() makes the local array accessible to the caller. Why is that? Is this somewhat like a memory leak?
The code (tested in Arduino 1.6.12, 64-bit Debian Jessie):
uint32_t timer;
void setup () {
Serial.begin(57600);
Serial.println("init");
}
void loop () {
if (millis() > timer) {
timer = millis() + 1000;
// many bytes need escaping, so we better use the URLencode function
byte testarray[3];
test(testarray);
Serial.print("testing: ");
Serial.println((char *) testarray);
Serial.println("---------");
}
}
void test(byte _b[]) {
byte c[4];
c[0] = 95; c[1] = 48; c[2] = 55; c[3] = 0;
_b = c;
Serial.println((char *) c); // MARKED: this is the line that causes the unexpected behaviour
}
With the MARKED line, I get the following output:
init
_07
testing: _07
---------
_07
testing: _07
---------
Without the MARKED line, I get this:
init
testing:
---------
testing:
---------
testing:
---------
testing:
---------
testing:
---------