Memory Allocation: Basics to Implementation

We all are aware of the fact that in Computer Science field or in IT field it is really mandatory to at least have the idea of Memory Allocation but we sometimes lack in understanding this topic.

Today, we are going to explain the Memory Allocation from very basic to some of its implementation and finally reach to its examples. So let’s get started with its definition.

Memory Allocation

Memory Allocation:

It refers to allocating or assigning memory to the program at the run time in programming context referred to as dynamic programming allocation and at the compile time referred as static memory allocation.The main task is to allocate memory at run time so that no amount of extra memory is wasted and the execution of the task is done in the most optimal way.

 

Now, we have the idea about Memory Allocation but it also comes in our mind that what will be its benefit, why should I use it, Is it always better to have or sometimes results badly. Below we’re providing some points to marks its merits and demerits:

 

Advantages:

  • Allocating memory is easy and cheap
  • Any free page is ok, OS can take first one out of list it keeps
  • Eliminates external fragmentation
  • Data (page frames) can be scattered all over PM
  • Pages are mapped appropriately anyway
  • Allows demand paging and pre-paging
  • More efficient swapping
  • No need for considerations about fragmentation
  • Just swap out page least likely to be used

 

Disadvantages:

  • Longer memory access times (page table lookup)
  • Can be improved using TLB
  • Guarded page tables
  • Inverted page tables
  • Memory requirements (one entry per VM page)
  • Improve using Multilevel page tables and variable page sizes (super-pages)
  • Guarded page tables
  • Page Table Length Register (PTLR) to limit virtual memory size
  • Internal fragmentation

After having the idea of advantages and disadvantages, we are discussing some function used in this. Memory allocation in C programming language is done with the help of following commands:-

  • Malloc
  • Calloc
  • Realloc
  • Free

 

Malloc:

Allocates the block of the memory from the memory heap generally expressed as ram.

Declaration:

Malloc – void malloc(size_t size)

 

Syntax:

int *ptr =(int*)malloc(10*sizeof(int));

Print ptr;

malloc of memory alloation

 

Explanation:

int *ptr =(int*)malloc(10*sizeof(int));

  • Here *ptr is our required pointer to store all the data.
  • (int*) is used for type casting
  • Malloc keyword instructs the system to use this particular method to allocate the required amount of memory.
  • 10 here is the size of the integer
  • ‘Sizeof()’ keyword instructs the computer to allocate the size according to data type passed in it.

Example:

void *ptr=(int*)malloc(4*sizeof(int));

In this below picture from 102 to 105, the memory is allocated.

memory alloation storage

 

Calloc:

The name calloc stands for “contiguous allocation”.

The only difference between malloc() and calloc() is that malloc() allocates a single block of memory whereas calloc() allocates multiple blocks of memory each of the same size and sets all bytes to zero.

 

Declaration:

Calloc – void calloc(size_t num,size_t size);

Syntax:

int *ptr =(int*)calloc(10,sizeof(int));

Print ptr;

 

Explanation:

int *ptr =(int*)calloc(10,sizeof(int));

  • Here *ptr is our required pointer to store all the data.
  • (int*) is used for type casting
  • Calloc keyword instructs the system to use this particular method to allocate the required amount of memory. Here multiple blocks of memory are allocated so they are arranged in continuous form inside the memory.
  • 10 here is the size of the integer.
  • ‘Sizeof()’ keyword instructs the computer to allocate the size according to data type passed in it.
  • In case of calloc, there is no wastage of memory. As we can see in malloc a full stack of block memory is allocate and data is stored in it leaving some amount of free space. But in case of calloc multiple blocks of memory are allocated and they are continuous so there is no scope for any garbage value to exist.

 

realloc:

If the previously allocated memory is insufficient or more than required, you can change the previously allocated memory size using realloc().

Declaration:

Void* realloc(void* ptr,size_t size);

 Syntax of realloc()

ptr = realloc(ptr,newsize);

Explanation:

  • Changes the initial size of allocated memory.
  • realloc deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size.
  • The contents of the new object are identical to that of the old object prior to deallocation, up to the lesser of the new and old sizes.
  • Any bytes in the new object beyond the size of the old object have indeterminate values.

 

free()

Dynamically allocated memory created with either calloc() or malloc() doesn’t get freed on its own. You must explicitly use free() to release the space.

syntax of free()

free(ptr);

This statement frees the space allocated in the memory pointed by ptr.

 

NOW LEARN THROUGH PROGRAM

We all have the theoretical idea of memory allocation but what about its examples or implementation. Yes, we also explain it with the help of examples. Hope it’ll help you to better understand the concept of it.

 

For Malloc

#include<stdio.h>

#include<stdlib.h>

int main()

{

   int n,i;

      printf("\n Enter The no. of elements");

      scanf("%d",&n);

   int *A =(int*)malloc(n*sizeof(int));

       for(i=0;i<n;i++)

       {

                A[i]=i+1;            //if we are not initializing A then default value is        

                                                     garbage value  

                   }



       for(i=0;i<n;i++)

       {

         printf("%d ",A[i]);

       }

}

 

OUTPUT OF THIS PROGRAM:

Enter The no. of elements

5

Output:

1   2    3    4    5

example of memory allocation

 

OUTPUT OF ABOVE PROGRAM WITHOUT INITIALIZATION:

      Enter The no. of elements

       5

     Output:

     13449504 13445368 1634887535 1818838637 2015916901

example of memory allocations

 

For Calloc

#include<stdio.h>

#include<stdlib.h>

int main()

{

   int n,i;

      printf("\n Enter The no. of elements");

      scanf("%d",&n);

   int *A =(int*)calloc(n,sizeof(int));

       for(i=0;i<n;i++)

       {

                A[i]=i+1;            //if we are not initializing A then default value is    

                                                                        0.

       }



       for(i=0;i<n;i++)

       {

         printf("%d ",A[i]);

       }



}

 


OUTPUT OF THIS PROGRAM:

Enter The no. of elements

5

Output:

1   2    3    4    5

example of memory allocation calloc

 

OUTPUT OF ABOVE PROGRAM WITHOUT INITIALIZATION:

Enter The no. of elements

5

Output:

0   0    0    0    0

example of memory allocation calloc1

 

For Realloc

#include<stdio.h>

#include<stdlib.h>

int main()

{

   int n,i;

      printf("\n Enter The no. of elements");

      scanf("%d",&n);

   int *A =(int*)malloc(n*sizeof(int));

       for(i=0;i<n;i++)

       {

                A[i]=i+1;

       }

       int *B=(int*)realloc(A,2*n*sizeof(int));

       for(i=0;i<2*n;i++)

       {

            printf("%d ",B[i]);

       }

       

}


OUTPUT OF THIS PROGRAM:

example of memory allocation realloc

 

So this is how reallocation takes place from first to the fifth element the same value is assigned but after fifth is garbage value due to malloc function if we will use calloc instead of malloc then after fifth the value will be zero.

 

Note:

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

 

 

A Blogger, a coder and IT Student

Leave a reply:

Your email address will not be published.