简体   繁体   English

从函数返回静态指针到局部变量

[英]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. 我唯一的犹豫是关于指针是static ,但我认为这没有任何改变,因为这是应该是static而不是指针的变量:局部变量将被破坏。 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();
    //...
}

For this code to be well-defined, both n and v would need to be static . 为了明确定义此代码, nv都需要是static

Right now, the *showNumber() has undefined behaviour as it dereferences a dangling pointer . 现在, *showNumber()具有未定义的行为,因为它取消引用悬空指针

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. 在这种情况下,返回的指针将包含相同的有效值。

Static variables persist for the entire duration of the program as soon as you initialize them. 一旦初始化,静态变量就会在程序的整个持续时间内持续存在。 You're all set for v , but not for n 's address. 你们都为v而设,但不是 n的地址。

If pointer and it's variable both are static then only code will be OK. 如果指针和它的变量都是静态的,那么只有代码才行。 Otherwise local variable will anyway going to die. 否则局部变量无论如何都会死亡。

Independent of local or global, static variable will live till the end of program. 独立于本地或全局,静态变量将一直持续到程序结束。 but it is recommenced that to use global when we return the value of that variable. 但是当我们返回该变量的值时,重新开始使用全局。 because static local may get affected due to threads. 因为静态本地可能会因线程而受到影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM