Weird pointer behaviour?

I have written a function which is supposed to return red, green and blue color values from a Neopixel packed 32Bit color value.

It works fine if I have a print line in the function. If i dont however, the function returns the wrong adress. Which seems weird, it shouldnt matter?

I am not really interested in an entirely different solution. I am trying to get used to using pointers and am wondering what could have caused this strange behaviour.

I am using the NodeMCU 1.0 which is using the ESP8266 if that matters in anyway.

This is how i use the function:

uint8_t* pt = decode32BitColor(color);
Serial.println((unsigned int)&pt); //Prints the adress of the returned pointer
storeInStruct(*pt++, *pt++, *pt);

And here it is:

uint8_t* decode32BitColor(uint32_t color) {
uint8_t buf[3];
buf[0] = (uint8_t)(color >> 16);
buf[1] = (uint8_t)(color >> 8 );
buf[2] = (uint8_t)(color);

Serial.println("-------"); //<------Has to be their??

return &buf[0];
}

If i print the adress of &buf[0] i get 0x3FFFFE40 and that is what the functions returns if i have a print line in the function. Is i remove it however the function returns 0x3FFFFE60 which is way off and i just get 0:s.

I am very thankful for responses.

The buffer is allocated when the function begins and goes away when the function ends. The printing slows things down enough so that it works, but programming this way is a bad practice as you can see.

By the way, I think that

storeInStruct(*pt++, *pt++, *pt);

is bad practice also because different compilers or even different versions of compilers may do the incrementing in differing orders.

You should have gotten a compiler warning for incorrectly trying to return a pointer to a local variable. If not, turn up the warning level in 'Preferences'.

vaj4088:
The buffer is allocated when the function begins and goes away when the function ends. The printing slows things down enough so that it works, but programming this way is a bad practice as you can see.

Alright thank you!
How should I do it?

gfvalvo:
You should have gotten a compiler warning for incorrectly trying to return a pointer to a local variable. If not, turn up the warning level in 'Preferences'.

Have done that now thanks!

There are various ways to fix the first problem. One quick way is to make the buffer global instead of local to the function.

Purists may hate this solution but it is a useful approach on processors with limited memory.

You can also make the buffer local or static / local to the calling function. Pass its pointer into the called function.