While programming it is extremely important, whenever we dynamically allocate the memory we have to delete it, otherwise, the memory will remain captured even tho your program has been exited. It is always a good practice to release the memory which allocated dynamically. You do not have to worry about compile time memory. It will be automatically deleted by the compiler as soon as you exit the program. It is the responsibility of the compiler to delete the compile time allocated memory.

C++ code to Allocate and delete the memory dynamically:

// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;


struct node{
    char info[15];
};

class trial{
    private:
    
        node obj1, *temp1, *temp2, *temp3;
        int i, length;
        char *p, *q;
        
    public:
        
        trial();
        ~trial();
        void startIn();
        
};

trial :: trial(){
    temp1, temp2, temp3 = NULL;
    p, q = NULL;
}

trial :: ~trial(){
    delete temp1;
    delete temp2;
    delete temp3;
}

void trial :: startIn(){
    cout<<"Making use of new and Delete Operator is as follows"<<endl;
    temp1 = new node;
    temp2 = new node;
    cout<<"Enter information about temp1"<<endl;
    cin>>temp1 -> info;
    cout<<"Enter information about temp2"<<endl;
    cin>>temp2 -> info;
    temp3 = &obj1;
    cout<<"Enter the information about temp3"<<endl;
    cin>>temp3 -> info;
    
    cout<<"Showing information of temp1"<<endl;
    cout<<temp1 -> info<<endl;
    cout<<"Showing information of temp2"<<endl;
    cout<<temp2 -> info<<endl;;
    cout<<"Showing information of temp3"<<endl;
    cout<<temp3 -> info<<endl;
    cout<<"Now enter the length of character array"<<endl;
    cin>>length;
    p = new char[length];
    q = p;
    cout<<"now enter "<<length<<" to fill the arry"<<endl;
    for(int i = 0; i <= length; i++){
        cin>>*p;
        p = p + 1;
    }
    
    p = q;
    
    cout<<"The elements of array are as follow"<<endl;
    for(int i=0; i<length; i++){
    cout<<*p;
    p = p +1;
    }
    p = q;
}

int main() {
    
    trial lnk;
    lnk.startIn();
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *