Freeing dynamically allocated memory - C++ Operator

C++ examples for Operator:delete

Description

Freeing dynamically allocated memory

Demo Code

#include <cstdlib> 
 #include <iostream> 

using namespace std; 

int main(int argc, char *argv []) 
{ 
    int *intPointer = NULL; 

    cout << "Allocating an integer..."; 
     intPointer = new int; 
    cout << "Done." << endl; 
    if (intPointer == NULL) 
    { /*from ww  w  . ja  v a2s  .c  o m*/
        cout << "Error: Could not allocate the integer." << endl; 
    } 
    else 
    { 
        cout << "Success: Integer was allocated" << endl; 
        cout << "Storing a 5 in the integer..."; 
        *intPointer = 5; 
        cout << "Done." << endl; 
        cout << "The integer = " << *intPointer << endl; 

        cout << "Freeing the allocated memory ..."; 
        delete intPointer; 
        cout << "Done." << endl; 

        cout << "Allocating 10 integers..."; 
        intPointer = new int [10]; 
        cout << "Done." << endl; 
    } 

    if (intPointer == NULL) 
    { 
        cout << "Error: Could not allocate 10 integers." << endl; 
    } 
    else 
    { 
        cout << "Storing 10 integers into the allocated memory "; 
        int *temp = intPointer; 
        int i = 0; 
        while (i < 10) 
        { 
            *temp = 10-i; 
            i++; 
            temp++; 
        } 

        cout << "Done." << endl; 

       cout << "Here are the 10 integers." << endl; 
        temp = intPointer; 
        i = 0; 
        while (i < 10) 
        { 
            cout << *temp << endl;; 
            i++; 
            temp++; 
        } 

        cout << "Freeing the allocated memory ..."; 
       delete [] intPointer; 
        cout << "Done." << endl; 
     } 
     return 0; 
 }

Result


Related Tutorials