在其生命周期内取消引用指向变量的指针
int* foo(int bar)
{
int baz = 6;
baz += bar;
return &baz; /* (&baz) copied to new memory location outside of foo. */
} /* (1) The lifetime of baz and bar end here as they have automatic storage
* duration (local variables), thus the returned pointer is not valid! */
int main (void)
{
int* p;
p = foo(5); /* (2) this expression's behavior is undefined */
*p = *p - 6; /* (3) Undefined behaviour here */
return 0;
}
一些编译器有助于指出这一点。例如,gcc
警告:
warning: function returns address of local variable [-Wreturn-local-addr]
和 clang
警告:
warning: address of stack memory associated with local variable 'baz' returned
[-Wreturn-stack-address]
对于上面的代码。但编译器可能无法在复杂的代码中提供帮助。
(1)返回对变量声明 static
的引用是已定义的行为,因为该变量在离开当前范围后未被销毁。
(2)根据 ISO / IEC 9899:20116.2.4§2,“当指向的对象到达其生命周期结束时,指针的值变得不确定。”
(3)取消引用函数 foo
返回的指针是未定义的行为,因为它引用的内存包含一个不确定的值。