Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Scope and lifetime are two different things, but they're related in the case of automatic (local) variables.

Scope is the region of program text in which an identifier is visible.

Lifetime is the duration during program execution in which an object (stored in memory) exists.

If you define a local variable, the scope of its identifier extends from its declaration to the end of the enclosing block; its lifetime is the execution of the enclosing block.

If you allocate an object on the heap by calling `malloc()`, its lifetime ends when its deallocated by calling `free()`.

An object defined at file scope or with the `static` keyword has a lifetime that's the entire execution of the program.

In either case, if you have a pointer to the object, that pointer becomes invalid when the object it points to reaches the end of its lifetime. (And C doesn't make it particularly difficult to cause problems by trying to access an object that no longer exists.)



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: