2.3 Dynamic

Variables cannot be allocated dynamically. However, objects without names can be allocated dynamically. Dynamically allocated objects can only be accessed by pointers (also known as handles).

A dynamically allocated object exists as soon as it is allocated. It ceases to exist only when the object is explicitly deallocated (freed or deleted).

Dynamically allocated objects have the advantage of on-demand like auto variables. However, it is better than auto variables because the lifespan of an dynamically allocated object does not depend on blocks, at all.

The following is an example to dynamically allocated and free objects.

struct X *p;

p = malloc(sizeof(struct X);
...
free(x);

Although this is an attribute of the implementation of dynamically allocated objects, it is important. The very nature of allocating storage dynamically leads to problems like memory fragmentation (using the malloc and free calls in C). In some other implementations, memory fragmentation is resolved by free space collection (garbage collection). However, this leads to other problems.



Copyright © 2006-08-28 by Tak Auyeung