Friday, October 16, 2009

1.6 Dynamic Memory Allocation

1.6.1 Static vs Dynamic Memory Allocation

The issue of efficient use of memory arises because of inefficiencies inherent in the way memory is allocated for arrays. When an array of size 1000 is declared, all 1000 memory location are reserved for the exclusive use of that array. No matter how many values you actually store in the array, you will always use 1000 memory locations. This strategy of memory allocation is termed as Static Allocation , in which all the memory that a data structure might possibly need is allocated at once without regard for the actual amount needed at execution time.

The opposite strategy, dynamic memory allocation, involves allocating memory on an as-needed basis. However, there always is an absolute maximum limit on allocation, that is the amount of memory that is physically available on the computer.

The difference between static and dynamic allocation is illustrated by the following example.

Example: Recording Names of Individuals

Suppose I have a total of 3000 memory locations available in which to store the first and last names of everyone in BCS class. If I use an array of strings to store this data, storage will be allocated statically, and consequently I must set a maximum on how long a name can be, and a maximum number of people in the class. It is quite hard to set these limits, especially when, as in this case, they interact: in order to allow longer names I have to reduce the possible size of the class. To be perfectly `safe' I would have to allow for those rare cases of people with extraordinarily long names, say 100 characters. Given that there are only 3000 memory locations in total, this name-size imposes a limit of 30 people per class. Now, this is clearly wrong. Even if there are 30-plus students with 100-character names, it is unthinkable that 30 of them will simultaneously register for the same course.

With dynamic allocation, I will not even have to think about how many people might join the class, or how long their names might be. I can just as easily accommodate 30 people with 100-character names and 300 people with 10-character names.

No comments:

Post a Comment