The C language supports two kinds of memory allocation through the variables in C programs:
Static allocation is what happens when you declare a static or global variable. Each static or global variable defines one block of space, of a fixed size. The space is allocated once, when your program is started, and is never freed.
Automatic allocation happens when you declare an automatic variable, such as a function argument or a local variable. The space for an automatic variable is allocated when the compound statement containing the declaration is entered, and is freed when that compound statement is exited.
In GNU C, the length of the automatic storage can be an expression that varies. In other C implementations, it must be a constant.
Dynamic allocation is not supported by C variables; there is no storage class ``dynamic'', and there can never be a C variable whose value is stored in dynamically allocated space. The only way to refer to dynamically allocated space is through a pointer. Because it is less convenient, and because the actual process of dynamic allocation requires more computation time, programmers use dynamic allocation only when neither static nor automatic allocation will serve.
For example, if you want to allocate dynamically some space to hold a struct foobar
, you cannot declare a variable of type struct foobar
whose contents are the dynamically allocated space. But you can declare a variable of pointer type struct foobar *
and assign it the address of the space. Then you can use the operators `*' and `->' on this pointer variable to refer to the contents of the space:
{ struct foobar *ptr = (struct foobar *) malloc (sizeof (struct foobar)); ptr->name = x; ptr->next = current_foobar; current_foobar = ptr; }