[go: up one dir, main page]

0% found this document useful (0 votes)
39 views14 pages

Dynamic Memory Allocation

The document explains memory allocation in C++, distinguishing between static (stack) and dynamic (heap) allocation. It covers the use of the 'new' and 'delete' operators for managing dynamic memory, including examples of allocating and deallocating single variables, arrays, and objects. Additionally, it highlights best practices to avoid memory leaks and dangling pointers.

Uploaded by

bennett.chatgpt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views14 pages

Dynamic Memory Allocation

The document explains memory allocation in C++, distinguishing between static (stack) and dynamic (heap) allocation. It covers the use of the 'new' and 'delete' operators for managing dynamic memory, including examples of allocating and deallocating single variables, arrays, and objects. Additionally, it highlights best practices to avoid memory leaks and dangling pointers.

Uploaded by

bennett.chatgpt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Dynamic Memory

Allocation C++
What is Memory Allocation?
In C++, when you create variables or objects, memory is
allocated to store their values. There are two primary ways
memory can be allocated:
• Static (or Stack) Allocation: Memory is allocated at
compile-time. The size and lifetime of variables are fixed.
Once the variable goes out of scope, the memory is
automatically deallocated.
• Dynamic (or Heap) Allocation: Memory is allocated at
runtime as needed. You have control over how much memory
to allocate and when to deallocate it. This is useful when you
don't know beforehand how much memory you'll need or
when you need to manage large amounts of data.
Why Use Dynamic Memory
Allocation?
• Flexibility: Allocate memory as needed during
program execution.
• Efficient Resource Use: Allocate large amounts of
memory without consuming stack space.
• Data Structures: Essential for implementing complex
data structures like linked lists, trees, and graphs.
The new Operator
• Purpose: Allocates memory on the heap for a single
variable or object and returns a pointer to it.

• pointer_variable = new data_type;


• int* ptr = new int; // Allocates memory for an integer
• *ptr = 10; // Assigns value to the allocated
memory
The delete Operator
• Purpose: Deallocates memory that was previously
allocated using new, freeing up resources.

• delete pointer_variable;
• pointer_variable = nullptr; // Good practice to avoid
dangling pointers

• delete ptr; // Deallocates memory


• ptr = nullptr; // Sets pointer to null
Note
• Always pair each new with a corresponding delete to
prevent memory leaks.
• Setting pointers to nullptr after deletion helps avoid
accessing invalid memory.
Creating objects
• There are two methods, first methods creates an object
in stack area, second one creates an object in heap
memory.
• Person p(“Name”, rollNo); //Stack allocation
• Person*p = new Person(“Name”, rollNo); //Heap
allocation
• // Deallocate memory
• delete personPtr;
• personPtr = nullptr;
• We deallocate the memory using delete, which calls the
destructor automatically.
Stack allocation
• The memory for the Person object p is allocated on the
stack.
• Stack memory is managed automatically by the system,
and it is typically faster to allocate and deallocate than
heap memory.
• It will be destroyed automatically when it goes out of
scope.
• Stack allocation is usually faster because it's just a
matter of adjusting the stack pointer.
• No explicit memory management is required.
Dynamic allocation
• The memory for the Person object is allocated on the heap.
• You get a pointer p that points to this heap-allocated Person
object.
• The Person object p has dynamic storage duration, meaning it will
persist until you explicitly deallocate it using delete.
• If you do not call delete, the memory will remain allocated,
leading to a memory leak.
• Heap allocation is generally slower than stack allocation because
it involves managing free memory, which can be fragmented.It
requires explicit memory management (delete), which introduces
the potential for errors (like memory leaks or dangling pointers).
Full Example:
#include <iostream>

int main() {
// Dynamic allocation
int* number = new int; // Allocates memory for an int
*number = 42; // Assigns value

std::cout << "Value: " << *number << std::endl;

// Deallocate memory
delete number;
number = nullptr; // Prevents dangling pointer

return 0;
}
Dynamic array allocation
• data_type* arrayName = new data_type[array_size];

• delete[] arrayName;
• arrayName = nullptr;

• Always use delete[] to deallocate memory allocated


with new[].
Example
int main() {
int size;
std::cout << "Enter the number of elements: ";
std::cin >> size;
// Dynamic array allocation
int* arr = new int[size];

// Initializing array elements


for(int i = 0; i < size; ++i) {
arr[i] = i * 2;
}
delete[] arr;
arr = nullptr;
return 0;
}
2D array
int main() {
int rows = 3; int cols = 4;
// Allocate memory for rows
int** matrix = new int*[rows];
// Allocate memory for columns
for(int i = 0; i < rows; ++i) {
matrix[i] = new int[cols];
}
// Initialize matrix
// Display matrix
// Deallocate memory
for(int i = 0; i < rows; ++i) {
delete[] matrix[i]; // Delete each row
}
delete[] matrix; // Delete array of pointers
matrix = nullptr;
return 0;
}
Pitfalls
• Always ensure that for every new or new[], there is a
corresponding delete or delete[], to avoid memory leaks.
• A pointer pointing to a memory location that has been
deleted (or freed) is called a dangling pointer.
• After deleting, set the pointer to nullptr.
• Always check if a pointer is nullptr before using it.
• int* ptr = new int(5);
• delete ptr;
• std::cout << *ptr; // Undefined behavior
• Mixing up new/delete with new[]/delete[].

You might also like