Memory allocation in C++ can be broadly classified into two categories: static memory allocation and dynamic memory allocation. Understanding the differences between these two types of memory allocation is crucial for efficient memory management in your programs.
Static memory allocation occurs at compile time. The memory for variables is allocated when the program is compiled, and it remains allocated throughout the program's execution. This type of allocation is typically used for global variables, static variables, and local variables that are defined with fixed sizes.
Global Variables:
int globalVar = 10; // Allocated statically
Static Local Variables:
void func() {
static int staticVar = 0; // Retains its value between function calls
staticVar++;
std::cout << staticVar << std::endl;
}
Array Declaration:
int arr[10]; // Allocated statically with fixed size
Dynamic memory allocation occurs at runtime. Memory is allocated on the heap as needed, and you can request and release memory during program execution. This flexibility is especially useful for managing variable-sized data structures, such as linked lists, trees, and arrays whose sizes are not known at compile time.
delete or free().Using new:
int* ptr = new int; // Allocates memory for a single integer
*ptr = 42; // Assign value to allocated memory
delete ptr; // Free the allocated memory
Allocating Arrays Dynamically:
int size;
std::cout << "Enter size: ";
std::cin >> size;
int* arr = new int[size]; // Allocates an array of integers
// Use the array...
delete[] arr; // Free the allocated array
Using std::vector:
The C++ Standard Library provides dynamic arrays through the std::vector class, which manages memory automatically.
#include <vector>
std::vector<int> vec; // Dynamic array
vec.push_back(1); // Adding elements dynamically
Static Allocation:
Dynamic Allocation:
delete or delete[] to free memory after use.Understanding static and dynamic memory allocation is crucial for effective memory management in C++. Static memory allocation is fixed and efficient, while dynamic memory allocation offers flexibility and scalability at the cost of some performance overhead. Knowing when to use each type can help you write more efficient and robust programs.
Open this section to load past papers