Skip to main content

Dynamic Memory Allocation

The key idea in dynamic memory allocation is to record all the available memory as a large pool that can be used for any purpose whatsoever. When you require some memory for your structure you ask for it and if it is available it is given from the pool. This memory allocation is done by a call to a procedure or function call. How this is programmed is different depending upon the high level language you are using.

Representing the memory pool available in the computer by one large block

However, the basic concept is the same. We can represent the memory pool available in the computer by one large block, as shown in the diagram alongside. We will use grey to indicate that this pool of memory is empty. All of the memory is free at present.

So what happens if we need to store the name "George"? Using a string to store this information would result in the allocation of enough space to hold the contents of the string. Generally in addition the memory allocator will also include a slight overhead for additional memory information. So, we can assume that we need a byte for each character stored in the string; in this instance we are storing 6 characters so we need six bytes. We also need a character at the end to indicate the end of the string, which will always take up one byte. In C this is called the 'NUL' character and is written "\0". We will ignore the memory allocation overhead; this may be one or two bytes and depends upon the implementation language.

Memory pool with 7 bytes allocated.We, therefore would require 7 bytes in order to store the information. In C we would request this memory by calling the malloc() function. The malloc function is the memory allocation routine. In Java we would create a new string by calling the new operation which performs the same task. What will happen? The memory allocation routine will allocate 7 bytes of memory to you. If we obtain the first 7 bytes from the pool then the memory pool may look as shown alongside.

The memory allocator keeps track of what memory is free and what memory has been allocated. It knows that the 7 bytes that it supplied to you are no longer free, ie: they are no longer in the global memory pool. We represent this fact by the sections that are no longer grey.

Next: Initialisation