Skip to main content

What is Dynamic Memory Allocation in C

Under stdlib header C provides us 4 four special function which helps in allocating memory dynamically and freeing it.

  • malloc()
  • calloc()
  • realloc()
  • free()
The first three function's are used in allocation of memory while the last one frees the allocated memory.

The Malloc function

Syntax


malloc(number_of_bytes);

The malloc function  allocates contiguous memory location for the required  number_of_bytes, returns a void pointer pointing to the base address of that allocated memory. A malloc returns a void pointer,why?because malloc does not know for what we allocated the memory (malloc does not know whether we are allocating memory for ints , floats or chars ).

Usage example


int *a=(int*malloc(5*sizeof(int));

The (int*) is done for typecasting, it converts the void pointer returned by malloc function to a integer pointer (int*) .

We are then assigning the returned(and type casted) pointer to a integer point a. So a is now pointing to the base address of allocated memory .

Let's look a complete code that uses a malloc function

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int n;
    printf("Enter the value of n\n");
    scanf("%d",&n);
    int *a=(int*malloc(n*sizeof(int));
    if(a==NULL){
       printf("Memory allocation failed");
       exit(1);
    }
    else
    {
     for(int i = 0 ; i < n ; i++)
    {
        printf("Enter number %d ",i+1);
        scanf("%d",(a+i));
    }
            printf("You entered\n");

    for(int i = 0 ;i < n ; i++)
    {
        printf("%d ",*(a+i));
    }
     free(a);
    }
    
}

We are including a header file stdlib because this is where our functions are defined.

So,basically we want to input N numbers from the user and display them.

At line 9.

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

We are dynamically allocating n*4 bytes of memory (size of a int is 4 bytes) . If n=5 then the function allocates 20 bytes of memory are returns a void pointer which is type casted to an integer pointer which is later assigned to a integer pointer a.

It is advised to check if the required memory is allocated or not this can be done by using the fact that malloc returns a NULL if memory cannot be allocated.

    if(a==NULL){
        printf("Memory allocation failed");
        exit(1);
    }

Remember that these function allocates contiguous memory.

So if  'a' points to the base address then 'a+1' points to the immediate next location after a.

Also the line 21 is equivalent to

        
scanf("%d",&a[i]);

This is  because pointers and Arrays are interchangeable in C.

Note that.


&a[i] is equivalent to (a+i).
a[i] is equivalent to *(a+i).


Line 29


free(a);

will be discussed later, just remember to free the allocated memory if it is of no use .

The calloc Function

Syntax


calloc(number_of_element,number_of_bytes);

The calloc function too allocates memory and returns a void pointer to that location.Unlike the malloc function it takes two arguments number_of_element and  number_of_bytes.

The above line of code is equivalent to 


malloc(n*sizeof(int));

However there is another difference between malloc and calloc function . It is,the memory allocated by calloc function initializes to zero.

Let us look at a complete example to demonstrate the use of calloc function

1.#include<stdio.h>
2.#include<stdlib.h>
3.
4.int main()
5.{
6.    int n;
7.   printf("Enter the value of n\n");
8.    scanf("%d",&n);
9.    int *a=(int*calloc(n,sizeof(int));
10.    if(a==NULL){
11.        printf("Memory allocation failed");
12.       exit(1);
13.    }
14.    else
15.   {
16.   for(int i = 0 ; i < n ; i++)
17.    {
18.        printf("Enter number %d ",i+1);
19.       scanf("%d",(a+i));
20.   }
21.          printf("You entered\n");
22.
23.    for(int i = 0 ; i < n ; i++)
24.    {
25.        printf("%d ",*(a+i));
26.    }
27.    free(a);
28.    }
29.}

The functionality is similar to the the former program instead we are just using calloc function here.

The Realloc Function

Syntax


realloc(*ptr,number_of_bytes);

Realloc is used to change (increase or decrease) the size of memory pointed by '*ptr' and changes it to 'number_of_bytes' . The newly initialized memory remains uninitialized.

If ptr is NULL then the call will be equivalent to


malloc(number_of_bytes);

if number_of_bytes is equal to zero it is equivalent to

     
free(ptr);

Note that only previously allocated memory can be reallocated.

A program to demonstrate the use of realloc function

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int n,n1=0;
    char choice;
    printf("Enter n\n");
    scanf("%d",&n);
    int *ptr = (int*calloc(n,sizeof(int));
    for (int i = 0i < ni++)
    {
        printf("Enter no %d ",i+1);
        scanf("%d",(ptr+i));
    }
    printf("Want to add more?Y/N\n");
    scanf(" %c",&choice);
    if(choice == 'Y'|| choice == 'y')
    {
     printf("How many more do you want");
     scanf("%d",&n1);
     ptr = (int*)realloc(ptr,(n+n1)*sizeof(int));
      for(int i = ni < n+n1 ; i++)
       {
         printf("Enter no %d ",i+1);
         scanf("%d",(ptr+i));
        }
    }
    printf("You entered\n");
    for(int i = 0 ;i <(n+n1);i++)
    {
        printf("%d ",*(ptr+i));
    }
    free(ptr);//memory freed here
}

In the above code we allocated certain bytes of memory using calloc function . However we came to know that the previously allocated memory was not enough for us, so we used the realloc function to reallocate the required size of memory.

The flow of above program goes like this:

We ask the user ,the total number he wants to input and then we allocate the required byte of memory using calloc function  and we again prompt the user asking if he/she wants to add more number if his answer is yes we ask how many more and reallocate the memory using realloc function . 

The free function

Memory is a valuable resource,we don't want to waste it . The free() function is for the same purpose.It frees the memory(deallocate) previously allocated by malloc , calloc and realloc function .

Syntax

    
free(ptr);

The above line of code causes the program to give back the block to the heap.

Although we have freed ptr it is not NULL it still contains some garbage value.

Memory Leak

Memory leak refers to the memory which has been previously allocated but is not freed(released) back after it is of no use . Memory leak may not affect the functionality of the program but may cause the program to crash .

A demonstration of memory leak

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int *ptr = (int*malloc(5*sizeof(int));
    int *A;
    *ptr = A;
}

The memory allocated by malloc function is not in any use but it is not released which causes memory leak.

It is advised to free all the allocated memory after it is of no use.

Why dynamic memory allocation over Arrays?

With arrays we have to declare the size of the the array while writing the program.The declared size sometimes may be inadequate or too abundant for our program . None of them are good for us.There is also no way to increase or decrease the size of array during execution of program.

All the problems mentioned above can be tackled using dynamic memory allocation ,we can manage memory properly using functions mentioned earlier.

Note that when we use array,static memory allocation takes place

Comments

Post a Comment

Popular posts from this blog

Making your own version of string handling function in C

 In the previous post we discussed about  string handling functions in C . In this post we'll be defining our own version for those function. Let's see how. xstrlen As the name suggests xstrlen will be function performing same functions as strlen function which returns the length of the string. # include < stdio.h > int   xstrlen ( char   * ); int   main () { char   name [] = " Abhilekh " ; printf ( " length is  %d " , xstrlen ( name )) ; return   0 ; } int   xstrlen ( char   * a) {      int   length   =   0 ;      while ( * a != ' \0 ' )     {        length ++ ;       a ++ ;     }      return   length ; } Look at the function prototype. int   xstrlen ( char   * ); It is very clear that the function is expecting a character pointer as a parameter and the function will be returning a integer value. Let us now see how we are calling the function, xstrlen ( name ) We are passing the name_of_array as a parameter. It should be noted that the name of

What is this Pointer in C++?

 Pointers are always headache for Programmers. However C++ have a special pointer which is referred as ' this '. The this pointer is one of the important concept in C++ and can be really confusing too. So in this article I will be discussing about the this pointer and its role in C++. The this Pointer Let us see an example first. # include < iostream > using   namespace  std; class   A { int   a ; public: // constructor A ( int   x   =   0 ): a ( x ){} void   display ()  const {      cout << a << ' \n ' ; } }; int   main (){ A   objA ( 10 ); A   objB ( 11 ); objA . display (); objB . display (); return   0 ; } It is very clear that the output will be 10 11 The program looks very simple, But do you know whats going on, under the Hood? How does the function remember, which object is invoking it? This is where the this pointer comes in action. Actually, the Compiler is secretly passing a constant pointer pointing to the object

File Handling and Various File Opening Modes in C

Every programs we were doing before were using Memory for storage and all those memory would wipe out once the program is terminated.But sometime the case is different,what if we need all those data again,We need to re-enter all those bulky data again,which will again be wiped out once the program is terminated. So we need to store the data in such a place such that it can be retrieved and displayed again and again.This is why we need files.The place about which we previously talked is the file on the disk.So we need File Handling to work with files. Let us see how a file can be handled. Various Operations in Files Creating a File Opening a File Reading from a File Writing to a File Closing a File File Opening Modes in C Before performing any operations in files,we must create/open the file . Here are the various File opening modes in C. "r" : It searches the file.If the file opens up successfully,the function fopen() loads the file from disk to memory and sets a pointer

What is Storage class and What are their types in C

 Variable declaration is not complete until we mention its storage class( there are some default conditions as well). Yeah you got it right ,Variables not only have data types they have storage class too. Why storage class? They tell us about The scope of the variable. Life time of the variable. Initial value of the the variable, if left unassigned. We have four storage class in C Automatic storage class External storage class Static storage class Register storage class Let us look at them one by one. Automatic Storage Class Scope : Local to the block where it is defined. Life Time : Until the control remains in the block. Initial value : A garbage value, one cannot predict. We use the keyword auto to declare a variable of automatic storage class. Demonstration of  Automatic storage class # include < stdio.h > void   myFunc (); int   main () {     auto  int   x   =   5 ;      printf ( " %d " , x ) ;      myFunc () ;      return   0 ; } void   myFunc () { int x;  

What is Structure and why do we need them in C

 In one of our previous post we dealt with Array .Here in this post we'll be dealing with structure which  I prefer to call 'The advanced version of arrays'. Structure Similar to an array, A structure is a collection, however of a dissimilar data types. Take an example of an office, Where the Manager wants to keep  the records of his/her employees.The record may include employees' name, address, department, pay scale , age and so on.So, why not create a variable with all those features in it. So when we want an entity with multiple features in it we can go with structures. First Glance of Structure struct   student {      int   rollNo , intake Year;      char   name [ 20 ], address [ 20 ]; }; Above is a structure student with some of the features of the student like:Roll number, intake year, their name and address. The keyword struct is used to define a structure. Structure definition always ends with a semicolon. The general form of Structure definition is struct   <

Arrays and static Memory allocation in C

In this post we will be talking about array, their usage and importance in C. Array Array in simple world is a collection/container of elements of  same type. Array of any type is possible but the elements in array cannot be of multiple types. We can have array of int type. But not a array with 5 element of int and other element of other types . Why Array? Imagine a problem where you want to input the marks of 10 student in a subject  from the user and display the marks in descending number. Our major problem above will be to store the number input by the user. Here we have two options : Either construct 10 variables for storing marks of 10 student .(A trash Idea) Or Construct a container (Array of integers in this case) which can store all the marks of student . First Glance of an Array As mentioned earlier array is a nothing else than a collection for us. int   marks [ 10 ]  =  { ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' }; This is what an array lo

Working with String Handling Functions in C

 C provides large set of string handling library function under string.h header. Few of them are discussed below. Strlen This function returns the length of the given string which is an integer value. Syntax strlen (name_of_array); The actual parameter for the function is the address of the first character of the array. Usage # include < stdio.h > # include < string.h > int   main () { char   name [] = " Abhilekh " ; printf ( " length is  %d " , strlen ( name )) ; return   0 ; } The output is: The  length  of the string is  8 Strcpy It should be noted that a string cannot be assigned to another string using a assignment operator(=). This is where we use this library function. It copies one string to another. Syntax strcpy (string1,string2); It copies the string from string2 to string1. Usage # include < stdio.h > # include < string.h > int   main () {   char   name [] = " Abhilekh " ;   char   copyName [ 8 ];   strcpy ( copyName , n

What is Operator Overloading in c++

  Who doesnot love syntactic sugar ? After all they make our code look more beautiful. So let us discuss how to  overload operators in C++ How to Overload Operators in C++ What if I tell you ,You can use most of the operator in C++ not only with built in type but with the  type you defined yourself (Classes are user defined type) .Yes you got it right , operator overloading lets you define the meaning of  an operator when used to operands of user defined type(classes) Overloaded operator are nothing else than a function (however a special one) with a special keyword operator followed by the symbol for the operator to be overloaded. As I already mentioned that overloaded opeartors are a function so they definetly have a return type,parameter(s) and a body. It should look something like this: returnType operator Symbol(){} As an example:   int   operator  +(){ // body } Let us now overload   plus operator (+) for our class . 1.# include < iostream > 2.using   namespace  std; 3. 4