C Programming language

C Programming Static and Dynamic memory allocation
Previous Home Next

Memory allocation in C Data Structures

Mainly Memory allocated to the Data Structures in following two ways :

  1. Static or compile time allocation
  2. Dynamic or runtime allocation

Static or Compile time allocation

It refers to the allocation of the memory to the program elements like identifiers, variables at the very beginning of the program. The amount of the memory allocated in this allocation scheme is fixed and cannot be manipulated.

For example,

int x, y;
float arr[5];

In the above declarations memory allocated to the variables x and y are a block of 2 bytes respectively where for the arr a memory block of 20 bytes is allocated consecutively, as we know in array  elements are stored consecutively. This allocation of memory is determined by the compiler at the compile time.

But this type of allocation scheme suffers from some limitations, for e.g. as we know that there is no bounds checking on the arrays in the C language, so if we store more than five elements in the above declared array then there will not be any type of error but the elements that are defined outside the bounds of the array will not be given consecutive memory locations infact they will be given some random memory locations for their storage, which will certainly violate the property of an array. On the other hand, if we define a lesser no. of elements than the actual containing capacity of an array then there will be sheer wastage of the memory which is not desired.

So to overcome the above  mentioned flaws of the static memory allocation scheme the concept of dynamic memory allocation came into existence.

Dynamic or runtime memory allocation

It means to allocate the memory to program elements during the runtime or the execution time of the program. In this type of allocation scheme the size of the program element can be increased or decreased dynamically according to the program requirement.

In C language the dynamic memory allocation is done via using pointers. This allocation scheme is best suited where we don't know the memory requirement in advance, which is the case with most of real life problems, which gives flexibility to the programmer.

There are some functions used for allocating and deallocating memory dynamically to the data structures.

Previous Home Next