Managing Memory in C++ - Dynamic Memory Allocation

A program for demonstrating dynamic memory allocation:

    #include <iostream>
    using namespace std;

    int main()
    {
        // declare a pointer to int and allocate space for it
        // with the keyword new
        int *pInt = new int; 

        // declare a pointer to double and allocate space for it
        // with the keyword new
        double *pDouble = new double;

        // store the value 3 in the memory location
        // pointed to by pInt
        *pInt = 3; 

        // store the value 5.0 in the memory location
        // pointed to by pDouble
        *pDouble = 5.0;

        //output the values and memory addresses
        std::cout << "value stored at pInt = " << *pInt << ": memory address = " << pInt << std::endl;
        std::cout << "value stored at pDouble = " << *pDouble << ": memory address = " << pDouble << std::endl;

        std::cout << "size of pInt = " << sizeof(pInt) ;
        std::cout << "size of *pInt = " << sizeof(*pInt) << std::endl;


        std::cout << "size of pDouble = " << sizeof(pDouble);
        std::cout << "size of *pDouble = " << sizeof(*pDouble) << std::endl;

        //let's now clean up the memory whe have used and realese that memory back to the operating system
        //otherwise our application has a memory leak

        delete pInt;
        delete pDouble;

        return 0;

    }

Note: Every time we have called the new keyword, at some point in our code, we are calling a delete keyword to release those memory resources. That will change a little bit when we start talking more about objects in the next module. Delete is used for these particular types of pointer (int, double ...)

Last updated