Professional Documents
Culture Documents
Chapter-13 Dynamic Memory Allocation (DMA)
Chapter-13 Dynamic Memory Allocation (DMA)
Chapter-13
Dynamic Memory Allocation (DMA)
Introduction
To store data we create variables in our program. This can be done by using data types.
In all our previous programs we wrote data type declaration instruction to specify
variables to the compiler. Compiler resolve declaration statements at compile time and
maintain variable related information in symbol table. Every time when program is
executing the first step is to allocate memory for this program in RAM. The amount of
memory allocated for variables depend on the information created by compiler at compile
time by looking at declaration statements. This is called static memory allocation.
The benefits of static memory allocation is its cost effective in terms of time. Since
decision of memory amount needed for variables are already done at compile time, no
extra time would be consumed for this purpose at the time of execution.
The major disadvantage of static memory allocation is lack of flexibility in memory
consumption. Since the decision regarding amount of memory has already been taken at
compile time no change could be made during run time.
There are scenarios where programmer is not sure about the amount of data to be handled
by the program. Static memory allocation is definitely a bad choice in such case. Solution
to this problem is dynamic memory allocation.
Decision of allocating memory to store data has taken at run time gives flexibility to the
programmer to make program efficient and cost effective in terms of memory
consumption.
Allocating memory at run time can be done by using either of two predefined functions:
1) malloc()
2) calloc()
We can also de-allocate memory using a predefined function free(). This function can
release memory that has been allocated previously by either malloc() or calloc() function.
Important to note
There are subtle differences between static memory allocation and dynamic memory
allocation. Memory blocks created by malloc() or calloc() has no name but can only be
access using their addresses.