Serial.println changes return value of function (A

2019-08-29 10:50发布

问题:

I've been experiencing some very odd behaviour from what should be a very simple function: an integer is passed to the function, and depending on its value will return an unsigned char specific to that integer.

I kept experiencing a problem in which it would return a different value to those that are hard coded into the function. I've had to rewrite the code a number of times to get it to stop happening, but I have found a way to recreate it every time to illustrate how something that shouldn't change the return value is doing.

Below is an example sketch to illustrate:

unsigned char* brokenFunction(int id)
{
    switch (id)
    {
        case 0:
        {
            //Serial.println("Break it...");
            unsigned char retval[8] = {
                0b01110,
                0b11011,
                0b10001,
                0b10001,
                0b10001,
                0b10001,
                0b10001,
                0b11111
            };

            return retval;
        }
        break;

        case 5:
        {
            unsigned char retval[8] = {
                0b01110,
                0b11011,
                0b11111,
                0b11111,
                0b11111,
                0b11111,
                0b11111,
                0b11111
            };

            return retval;
        }
        break;
    }
}

void setup()
{
    Serial.begin(9600);
    unsigned char* array = brokenFunction(0);
    Serial.println(*array);
}

void loop()
{

}

On line 7 is a call to Serial.println which is currently commented out. If you run the sketch on your Arduino with this line commented out, the Serial.println call in the setup function will return the value 14 (which is correct).

If, however, you uncomment line 7, the Serial.println call in the setup function will now return what seems like a random value; for my last test it was the value 91; see the serial window log below:

14 Break it... 91

As you can see, my first attempt returned 14, but the subsequent attempt with the extra Serial.println call resulted in the return value being changed.

Does anyone have any idea what may be going wrong here? There were other things I did that managed to replicate this too, but this is the most simple one to use as an example. It's almost as if, if the function is taking a bit longer to finish that the return value is being corrupted some how.

Any help or ideas would be much appreciated.

回答1:

You are returning a local array from the function brokenFunction(int id), which stops existing when you return, causing undefined behavior from that point on.