将指向局部变量的指针传递给函数:它安全吗?指针、变量、局部、函数

2023-09-07 03:05:24 作者:-゛二愣子

例如:

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

func1调用func2时,一个指向局部变量的指针被传递给func2——指针指向堆栈.这对 C 的规则安全吗?

When func1 calling func2, a pointer to local variable is passed to func2 -- the pointer is pointed to the stack. Is this safe for the rules of C?

谢谢.

推荐答案

i的作用域是func1,它比调用func2.所以绝对安全.

The scope of i is func1 and it outlives the call to func2. So it is perfectly safe.