Passing pointer to local variable to function: is it safe?

后端 未结 6 2118
余生分开走
余生分开走 2020-12-15 20:15

For example:

void func1(){
    int i = 123;
    func2(&i);
}
void func2(int *a){
    *a = 456;
}

When func1 calling

6条回答
  •  醉梦人生
    2020-12-15 21:05

    In your case, you can safely use &i till the time i is valid.

    Now, as we can see i has a lifetime till the end of func1(). As, the func2() is being called from the func1() and the func1() has not yet finished execution, so, i is still valid.

    That's why , usually passing the address of a local variable to another function is usually allowed (the variable's lifetime is not over) but, returning the address of a local variable (immediately after return, local variables of the function cease to exist) is not allowed.

    TL;DR :You can safely use &i as the argument of func2() as shown here.

提交回复
热议问题