Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning static pointer to local variable from function

I've found this code on web as an example, but I think this is not correct. An address to automatic variable is returned and this is just coincidence that it might work sometimes:

returning a pointer to an destroyed local variable, which becomes invalid memory location, is undefined behavior.

My only little hesitancy is about the pointer being static, but I think this changes nothing as this is the variable that should be static not a pointer: local variable is going to be destroyed. Can you please confirm or deny?

double *& showNumber()
{
    double n = 1550.85;
    static double *v = &n;
    return v;
}

int main(int argc, char *argv[])
{
    double sn = *showNumber();
    sn = *showNumber();
    //...
}
like image 916
4pie0 Avatar asked Dec 22 '25 15:12

4pie0


2 Answers

For this code to be well-defined, both n and v would need to be static.

Right now, the *showNumber() has undefined behaviour as it dereferences a dangling pointer.

like image 178
NPE Avatar answered Dec 24 '25 04:12

NPE


Your code has still undefined behaviour because the value of the static pointer is invalid after exiting the function. The local variable refered to by the pointer will be destroyed.And any next time when the function will be called the address of this local variable can be different.

You could write your function the following way

double * showNumber()
{
    static double n = 1550.85;
    return &n;
}

In this case the returned pointer would contain the same valid value.

like image 33
Vlad from Moscow Avatar answered Dec 24 '25 05:12

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!