LECTURE 24: Dynamic Data Structures (Chapter 14)

 

Read 14.1 – About pointer

 

Dynamic Memory Allocation

 

This allows us to use memory in a more efficient manner.

 

In C, upon variable declaration, the memory space that is reserved to store the variable is kept until the end of the function is reached. This can be inefficient in memory intensive applications.

 

Dynamic memory allocation allows a programmer to reserve memory when it is needed and to release it as soon as it is not needed.

 

Let us consider a standard code such as:

      ...

{

int num;

char let;

planet_t planet;

 

...

num = 307;

let = ‘Q’;

planet.diameter = 3.01;

...

}

 

Note: Memory that stores values of num, let, planet is reserved until the end of function is needed

FIGURE 14.3 illustrates memory after declaration of variables num, let, planet

 

Let us consider an alternative solution:

...

{

int *nump;

char *letp;

planet_t *planet;

 

...

nump = (int *)malloc(sizeof(int));

letp = (char *)malloc(sizeof(char));

planetp = (planet_t *)malloc(sizeof(planet_t));

 

*nump = 307;

*letp = ‘Q’;

planetp->diameter = 3.01;

 

free(letp);

free(planetp);

...

}

 

Note: memory to store values of integer, char, planet_t variables is reserved upon call to malloc function, and is released upon call to free function!!

 

Note: Part of memory where malloc allocates memory is called HEAP. The remaining part of memory is called STACK.

 

FIGURE 14.4 illustrates STACK and HEAP memory after call to malloc function, while FIGURE 14.5 illustrates it after values are assigned to dynamically allocated variables

 

Function malloc is used to allocate a single memory block for any built-in or user-defined type. Function calloc allows dynamic array allocation. For example, the following piece of code allocates memory for a string of size 50:

char *string1;

string1 = (char *)calloc(50,sizewof(str));

 

Linked Lists

 

Read 14.3