Previous Page
Next Page

11.5. Storage Duration of Objects

During the execution of the program, each object exists as a location in memory for a certain period, called its lifetime . There is no way to access an object before or after its lifetime. For example, the value of a pointer becomes invalid when the object that it references reaches the end of its lifetime.

In C, the lifetime of an object is determined by its storage duration . Objects in C have one of three kinds of storage duration: static, automatic, or allocated. C does not specify how objects must actually be stored in any particular system architecture, but typically, objects with static storage duration are located in a data segment of the program in memory, while objects with automatic storage duration are located on the stack. Allocated storage is memory that the program obtains at runtime by calling the malloc( ), calloc( ), and realloc( ) functions. Dynamic storage allocation is described in Chapter 12.

11.5.1. Static Storage Duration

Objects that are defined outside all functions, or within a function and with the storage class specifier static, have static storage duration . These include all objects whose identifiers have internal or external linkage.

All objects with static storage duration are generated and initialized before execution of the program begins. Their lifetime spans the program's entire runtime.

11.5.2. Automatic Storage Duration

Objects defined within a function and with no storage class specifier (or with the unnecessary specifier auto) have automatic storage duration. Function parameters also have automatic storage duration. Objects with automatic storage duration are generally called automatic variables for short.

The lifetime of an automatic object is delimited by the braces ({}) that begin and end the block in which the object is defined. Variable-length arrays are an exception: their lifetime begins at the point of declaration, and ends with the identifier's scopethat is, at the end of the block containing the declaration, or when a jump occurs to a point before the declaration.

Each time the flow of program execution enters a block, new instances of any automatic objects defined in the block are generated (and initialized, if the declaration includes an initializer). This fact is important in recursive functions, for example.


Previous Page
Next Page