Mark As Completed Discussion

Dynamic Memory Allocation

In C++, memory can be allocated dynamically using the new operator. This allows us to allocate memory at runtime and access it through pointers.

Let's look at an example:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  int* p = new int;  // Allocate memory
6  *p = 5;  // Assign value
7
8  cout << "Value at p: " << *p << endl;
9
10  delete p;  // Deallocate memory
11
12  return 0;
13}

In this example, we declare an integer pointer p and allocate memory for an integer using the new operator. We then assign a value of 5 to the memory location pointed to by p.

Executing the code will output:

SNIPPET
1Value at p: 5

After we are done using the dynamically allocated memory, it is important to deallocate it using the delete operator. Failure to do so can result in memory leaks and inefficient memory usage.

Dynamic memory allocation is particularly useful when we don't know the size of the memory required at compile time or when we want to allocate memory on the heap instead of the stack.

Keep in mind that whenever you allocate memory dynamically, it is your responsibility to deallocate it when it is no longer needed to avoid memory leaks.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment