Topic :Dynamic Memory allocation using Malloc() function in C++ Programming Language:

Malloc():

In our previous tutorial New Operator we discuss about the dynamic memory allocation using New Operator. In this tutorial we will allocate Dynamic memory using Malloc() function. Old C Library <stdlib.h> Provide Malloc() function to allocate Runtime memory.

Same like New operator, Malloc() function dynamically allocate memory and returns a pointer to the first byte of memory location of specified size allocated from the heap. and if there is no enough space that we want to allocate, this function will return a "NULL" pointer. the basic syntax is:




void * malloc (Size_in_byte);


This function returns a void pointer to the allocated Memory. if there is insufficient memory available, then it will return NULL. Malloc() function need an argument, that is size in bytes of that area we want to reserve.

If we want pointer to return other type then void, then we can use type cast Operator on the return value. the syntax is here:



cast_type *ptr; //Pointer to Data_type
ptr = (Cast_type *)malloc(Size_in_byte);


In above example, we declared an pointer of cast-type. then malloc() function need the size in bytes. so we can use sizeof() Operator here to allocate the exact size. Finally our syntax will be:




int *ptr; //Pointer to int
ptr = (int*)malloc(sizeof(int));



The Use of sizeof() Operator tends to look like a function call. but it's an operator as we know. and it doesn't work at compile time.



Let's have an simple example here to understand, how this function work to allocate memory dynamically.



/*Example: Malloc() Function: InfoBrother */

#include<iostream>
#include<stdlib.h> //Required for Malloc function:
using namespace std;

main()
{
    int *ptr,*ptr2; //(*ptr) Use to allocate memory:
//(*ptr2) will use to display the result:
int num,sum=0; //num is the number of bites,

cout<<" Enter Total Number of element to be input: ";
cin>>num;

ptr=(int*)malloc(num*sizeof(int)); //Memory allocation:
ptr=ptr2;

cout<<" Please Enter Your "<<num<<" Elements: "<<endl;
for(int i=1;i<=num;i++) //Loop to store data.
{
    cout<<" Element # "<<i<<") ";
    cin>>*ptr;
    sum+=*ptr; //will add all numbers;
    ptr++;        
}
    
cout<<" \n\n Your Enter: "<<endl;
for(int i=1;i<=num;i++) //Loop to display the result:
{
    cout<<" Element # "<<i<<") ";
    cout<<*ptr2<<endl;
    *ptr2++;
}

cout<<" The Sum of these Number are: "<<sum;

return 0;
}


We just write simple example, where we allocate dynamic memory using Malloc() function. This function allocates enough memory from the heap and store some element and return their sum. As we know that if malloc() is unable to allocate the requested memory, it will return a NULL pointer. and a NULL pointer points Definitely nowhere. so, if we try to use that NULL pointer that's point to nothing, then our program probably won't last long. so it’s always better if our program contains an error checker. so we can know if malloc() is unable to allocate requested memory. so after adding error checker our program will look like this.



/*Example: Malloc() Function: InfoBrother */

#include<iostream>
#include<stdlib.h> //Required for Malloc function:
using namespace std;

main()
{
    int *ptr,*ptr2; //(*ptr) Use to allocate memory:
//(*ptr2) will use to display the result:
int num,sum=0; //num is the number of bites,

cout<<" Enter Total Number of element to be input: ";
cin>>num;

ptr=(int*)malloc(num*sizeof(int)); //Memory allocation:
ptr=ptr2;

if(ptr==NULL) //Error checker:
{
    cout<<" An Error Occur While Memory Allocation: "<<endl;
    exit(0);
}

else
{
    cout<<" Please Enter Your "<<num<<" Elements: "<<endl;
    for(int i=1;i<=num;i++) //Loop to store data.
     {
    cout<<" Element # "<<i<<") ";
        cin>>*ptr;
        sum+=*ptr; //will add all numbers;
        ptr++;        
}

    
    cout<<" \n\n Your Enter: "<<endl;
    for(int i=1;i<=num;i++) //Loop to display the result:
     {
        cout<<" Element # "<<i<<") ";
        cout<<*ptr2<<endl;
        *ptr2++;
}

cout<<" The Sum of these Number are: "<<sum;

}

return 0;
}


Remember, we allocate Memory dynamically using Malloc() function. this memory was allocated from heap. as its from heap so we are responsible to release this memory once its free and we don't need it more.



Now at the end we need to release the allocated memory. In our Previous tutorial, We use an Operator Delete to release the memory that was allocated using New Operator. in C, we have another function free() to release the Memory that was allocated using Malloc() function. Now let's back to same function and free the memory that was allocated dynamically.



/*Example: Malloc() Function: InfoBrother */

#include<iostream>
#include<stdlib.h> //Required for Malloc function:
using namespace std;

main()
{
    int *ptr,*ptr2; //(*ptr) Use to allocate memory:
//(*ptr2) will use to display the result:
int num,sum=0; //num is the number of bites,

cout<<" Enter Total Number of element to be input: ";
cin>>num;

ptr=(int*)malloc(num*sizeof(int)); //Memory allocation:
ptr=ptr2;

if(ptr==NULL) //Error checker:
{
    cout<<" An Error Occur While Memory Allocation: "<<endl;
    exit(0);
}

else
{
    cout<<" Please Enter Your "<<num<<" Elements: "<<endl;
    for(int i=1;i<=num;i++) //Loop to store data.
     {
    cout<<" Element # "<<i<<") ";
        cin>>*ptr;
        sum+=*ptr; //will add all numbers;
        ptr++;        
}
    
    cout<<" \n\n Your Enter: "<<endl;
    for(int i=1;i<=num;i++) //Loop to display the result:
     {
        cout<<" Element # "<<i<<") ";
        cout<<*ptr2<<endl;
        *ptr2++;
}

cout<<" The Sum of these Number are: "<<sum;
}

free(ptr); //free the memory:

return 0;
}


The malloc() Function is an old function of C Programming, but still, it exists in C++, but it is better to avoid using malloc() function. The main advantage of New over Malloc() is that New doesn't just allocate memory, it constructs objects which is prime purpose of C++.







I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement