Please enable JavaScript.
Coggle requires JavaScript to display documents.
Dynamic Memory Allocation - Coggle Diagram
Dynamic Memory Allocation
Overview
Purpose: Allocate memory at runtime for flexibility.
Usage: Useful for dynamic data structures (e.g., trees, linked lists).
Memory: Uses the heap for memory storage.
Flexibility: Memory can be released to optimize usage.
Key Concepts
Operators:
new: Allocates memory dynamically.
delete: Releases dynamically allocated memory.
Error Handling:
new calls a new handler if memory allocation fails.
Exceptions: Uncaught exceptions terminate the program.
Memory Allocation
Syntax: ptr = new type;
Creates an object of type and returns its address.
Example: double* ptr = new double(10.5);
Array Allocation:
new[] allocates a dynamic array.
Example: int* arr = new int[10];
Memory Deallocation
Syntax: delete ptr; or delete[] arr;
Rules
Only release dynamically allocated memory.
Avoid double-deleting pointers.
Do not use delete for static allocations.
Common Errors
Misuse of delete:
Double deletion.
Deleting non-dynamic memory.
Null Pointer Handling:
Deleting a NULL pointer does nothing safely.
Dynamic Data Structures
Types:
Linked Lists: Nodes connected via pointers.
Dynamic Arrays: Resizable arrays using new[] and delete[].
Advantages:
Allocates memory as needed.
Easier insertion/deletion compared to static structures.
Class-Specific Allocation
new with Constructors:
Allocates memory and calls the class constructor.
delete with Destructors:
Calls destructor before releasing memory.