# 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 ...)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lamhung81-2.gitbook.io/learning-c/managing-memory-in-c++-dynamic-memory-allocation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
