?
This document uses PHP Chinese website manual Release
C中的每個(gè)對(duì)象都有一個(gè)常量地址,保留其最后存儲(chǔ)的值(除非值是不確定的),并且對(duì)于VLA來說,它的大?。ㄗ訡99以來)保持在被稱為該對(duì)象生命周期的一部分程序執(zhí)行中。
對(duì)于使用自動(dòng),靜態(tài)和線程存儲(chǔ)持續(xù)時(shí)間聲明的對(duì)象,壽命等于它們的存儲(chǔ)持續(xù)時(shí)間(請(qǐng)注意非VLA和VLA自動(dòng)存儲(chǔ)持續(xù)時(shí)間之間的差異)。
對(duì)于具有已分配存儲(chǔ)持續(xù)時(shí)間的對(duì)象,生命周期從分配函數(shù)返回(包括從中返回realloc
)開始,并在realloc
調(diào)用或釋放函數(shù)被調(diào)用時(shí)結(jié)束。請(qǐng)注意,由于分配的對(duì)象沒有聲明類型,所以首先用于訪問此對(duì)象的左值表達(dá)式的類型成為其有效類型。
在其生命周期外訪問對(duì)象是未定義的行為。
int* foo(void) { int a = 17; // a has automatic storage duration return &a;} // lifetime of a endsint main(void) { int* p = foo(); // p points to an object past lifetime ("dangling pointer") int n = *p; // undefined behavior}
指向其生命周期結(jié)束的對(duì)象(或?qū)ο笾蟮膶?duì)象)的指針具有不確定的值。
包含由非左值表達(dá)式指定的數(shù)組成員(直接或嵌套結(jié)構(gòu)/聯(lián)合成員的成員)的結(jié)構(gòu)和聯(lián)合對(duì)象具有臨時(shí)生存期。當(dāng)包含完整表達(dá)式或完整聲明程序結(jié)束時(shí)(自C11開始),對(duì)引用此類對(duì)象的表達(dá)式進(jìn)行評(píng)估并結(jié)束于下一個(gè)序列點(diǎn)(直到C11)時(shí)臨時(shí)生存期開始。
任何嘗試修改具有臨時(shí)生命周期的對(duì)象都會(huì)導(dǎo)致未定義的行為。
struct T { double a[4]; };struct T f(void) { return (struct T){3.15}; }double g1(double* x) { return *x; }void g2(double* x) { *x = 1.0; }int main(void){ double d = g1(f().a); // C99: UB access to a[0] in g1 whose lifetime ended // at the sequence point at the start of g1 // C11: OK, d is 3.15 g2(f().a); // C99: UB modification of a[0] whose lifetime ended at the sequence point // C11: UB attempt to modify a temporary object}
C11 standard (ISO/IEC 9899:2011):
6.2.4 Storage durations of objects (p: 38-39)
C99 standard (ISO/IEC 9899:1999):
6.2.4 Storage durations of objects (p: 32)
C89/C90 standard (ISO/IEC 9899:1990):
3.1.2.4 Storage durations of objects