简体   繁体   中英

Serial.println changes return value of function (Arduino)

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.

您正在从函数brokenFunction(int id)返回一个本地数组,该函数在您返回时停止存在,从而导致该点的未定义行为。

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