Memory Allocation

Deep dive into memory allocation process in C++.

Memory Allocation

Memory allocation and deallocation are fundamental operations that programmers need to understand to manage memory effectively. There are two main ways to allocate memory in C++: static memory allocation and dynamic memory allocation.

1. Static Memory Allocation:

  • Static memory allocation is done at compile time.
  • Memory is allocated at the time of program execution and remains constant throughout the program's execution.
  • Variables declared with keywords like 'int', 'float', 'char', etc., are examples of statically allocated memory.
  • Memory is allocated on the stack for local variables and in the data segment for global variables.

Syntax:

int main() {
    int staticVar; // statically allocated on the stack
    staticVar = 10;
    // ...
    return 0;
}

2. Dynamic Memory Allocation:

  • Dynamic memory allocation is done at runtime.
  • The 'new' keyword is used to allocate memory dynamically, and 'delete' is used to deallocate it.
  • Memory is allocated on the heap, and the programmer is responsible for managing the allocated memory.
  • Dynamic memory allocation is useful when you need memory whose size is not known until runtime or when you need to manage memory explicitly.

Syntax:

int main() {
    int* dynamicVar = new int; // dynamically allocated on the heap
    *dynamicVar = 20;
    // ...
    delete dynamicVar; // deallocating the memory
    return 0;
}

The C++11 standard introduced smart pointers, like 'std::unique_ptr' and 'std::shared_ptr', which help manage dynamic memory more safely by automatically deallocating memory when it is no longer needed. They are part of the C++ Standard Library's '<memory>' header.

The '<memory>' header in C++ provides several components for managing dynamic memory (heap memory) and creating smart pointers.

unique_ptr

Prefer 'std::unique_ptr' when you want exclusive ownership of a resource and don't need shared ownership.

Example using 'std::unique_ptr':

cpp Copy Code
#include <iostream>
#include <memory>

int main() {
    std::unique_ptr<int> uniquePtr(new int(42));
    std::cout << "Value stored in unique_ptr: " << *uniquePtr << std::endl;
// Memory is automatically released when uniquePtr goes out of scope
    return 0; 
}
Output:
Value stored in unique_ptr: 42

shared_ptr

Use 'std::shared_ptr' when you need shared ownership of a resource, allowing multiple pointers to access and manage the same object.

Example using 'std::shared_ptr':

cpp Copy Code
#include <iostream>
#include <memory>

int main() {

    // Both sharedPtr1 and sharedPtr2 own the dynamically allocated integer
    std::shared_ptr<int> sharedPtr1 = std::make_shared<int>(42);
    std::shared_ptr<int> sharedPtr2 = sharedPtr1;

 // Print the values using both shared_ptrs
    std::cout << "Value stored in sharedPtr1: " << *sharedPtr1 << std::endl;
    std::cout << "Value stored in sharedPtr2: " << *sharedPtr2 << std::endl;

// Print the use_count
    std::cout << "sharedPtr1 count: " << sharedPtr1.use_count() << std::endl;
    std::cout << "sharedPtr2 count: " << sharedPtr2.use_count() << std::endl;

//Memory is released when the last shared_ptr resource goes out of scope
    return 0;
}

* The 'use_count()' is a member function of 'std::shared_ptr' in C++, and it returns the number of 'shared_ptr' objects sharing ownership of the same dynamically allocated object. It gives you an indication of how many shared_ptr instances are managing the same resource.

Output:
Value stored in sharedPtr1: 42     
Value stored in sharedPtr2: 42     
sharedPtr1 count: 2
sharedPtr2 count: 2

Note: Understanding memory allocation and deallocation is crucial for writing efficient and bug-free C++ code, especially when dealing with complex data structures or resource management.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.