在其生命週期內取消引用指向變數的指標

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 返回的指標是未定義的行為,因為它引用的記憶體包含一個不確定的值。