C++.Module 02
C++.Module 02
and the control flow of a program. It operates in a Last-In-First-Out (LIFO) manner, meaning
the last function or variable added is the first to be removed. Stack memory is automatically
managed by the system.
Key Features:
1. Memory Allocation:
o Memory is automatically allocated when a function is called and deallocated when
the function returns.
o No manual intervention is required for memory management.
2. Size:
o Stack memory is relatively small and has a fixed size, typically limited by the
system (usually a few MBs).
o Exceeding the stack's limit results in a Stack Overflow error, which can occur due
to excessive recursion or too many nested function calls.
3. Speed:
o Access to stack memory is fast due to its simple LIFO structure.
4. Scope:
o Variables in stack memory are local to the function they are declared in.
o Once the function completes, the variables are automatically removed from
memory.
5. Memory Layout:
o The stack grows and shrinks as functions are called and return.
o Each function call reserves a block of memory called a stack frame. This stack
frame stores local variables, parameters, and the return address (the point where the
program resumes after the function completes).
Key Features:
1. Memory Allocation:
o Memory is allocated explicitly using functions like malloc(), calloc(), or new in
languages like C/C++, and freed using free() or delete.
o In languages like Java and Python, memory is managed through garbage collection,
which automatically reclaims unused memory.
2. Size:
o Heap memory is much larger compared to the stack and is typically limited only by
the system’s available memory.
o It is well-suited for creating large and dynamic data structures such as arrays, linked
lists, trees, and graphs.
3. Speed:
o Access to heap memory is slower than stack memory due to its flexible allocation,
requiring more complex memory management, including searching, fragmentation,
and defragmentation.
4. Scope:
o Variables stored in the heap are globally accessible as long as a pointer or reference
exists. These variables are not restricted to the function in which they were created.
5. Memory Layout:
o Unlike stack memory, heap memory grows and shrinks in a less structured manner,
expanding or contracting based on system resources.
o Manual management of heap memory introduces risks such as memory leaks if
memory is not explicitly deallocated.
Use Cases:
1. Stack:
o Use stack memory for small variables with short lifespans, like local variables in
functions.
o Suitable for simple, short-term memory needs.
2. Heap:
o Use heap memory for large or complex data structures that need to persist
beyond the scope of the function that created them.
o Ideal for dynamic data where the size or amount of data is not known at compile
time (e.g., dynamically resizing arrays, linked lists).
Common Issues
1. Stack Overflow:
o Occurs when there are too many nested function calls or when recursion depth
exceeds the stack limit.
o Example: Deep recursion without base case in a recursive function.
2. Memory Leak (Heap):
o Happens when memory is allocated in the heap but not freed after use.
o Over time, it can lead to exhaustion of available memory, causing the program or
system to crash.
3. Dangling Pointer (Heap):
o Refers to a pointer that still points to a location in the heap even after the memory
has been freed, leading to undefined behavior if dereferenced.
Key Differences
Visual Representation
main()
{
int *a = func();
} এখোলে, main()-এর ‘a’ শুধু func()-এর ‘a’-এর
‘a[0]’-এর অ্যোলেস পোলব, ডোটো পোলব েো। কোরণ,
int* func()
func()-এর কোজ প্েষ হলয় প্গলল Stack প্মলমোকর
{
int a = {2, 5, 6}; প্েলক এর সব ডোটো মু লছ যোলব।
return a;
}
Stack প্মলমোকরর এই অ্সু কবধোগুললো সলভ্ কলর Heap প্মলমোকর। Heap প্মলমোকরর ডোটো অ্লটোলমটিককল করমু ভ্ হয় েো;
আমোলদরলক মযোেু য়োকল করমু ভ্ করলে হয়।
Use malloc(), calloc(), or new (based on the language) to allocate memory dynamically in the heap,
accessible via pointers or references. stdlib.h header file is needed to include for malloc and calloc.
int main()
{
cout << new int << endl;
*ip = 11;
*fp = 11.5467;
return 0;
}
❖ Heap প্মলমোকরলক সরোসকর অ্যোলেস করো যোয় েো, Stack প্মলমোকরলক করো যোয়।
❖ Heap প্মলমোকর অ্যোলেস করটোেথ কলর, েোই ডোটো টোইপ অ্েুযোয়ী পলয়ন্টোর কডলেআ করলে হয়।
❖ অ্যোলরই সোইজ বোড়োলে হলল, ককিংবো ফোিংেে প্েলক অ্যোলরই করটোেথ করলে হলল Heap প্মলমোকর অ্যোলেস করলে হয়।
Stack Heap
a 1X02A
int *ip = new int[5]; new int;
Stack Heap
ip 1X02A
#include <bits/stdc++.h>
int main()
for (int i = 0; i < 5; i++)
{
{
int *iarr = new int[5];
cin >> farr[i];
}
iarr[0] = 3;
iarr[1] = 4;
for (int i = 0; i < 5; i++)
iarr[2] = 5;
{
iarr[3] = 6;
cout << farr[i] << " ";
iarr[4] = 7;
}
#include <bits/stdc++.h>
int main()
{
int *arr0 = new int[5];
arr1[5] = 9;
arr1[6] = 10;
delete[] arr1;
return 0;
}
Note:
1. To delete a single variable: delete variable_name;
2. To delete an array: delete[] array_name;
The function allocates the array and returns a pointer to it. The caller function is responsible for
deallocating the array.
#include <bits/stdc++.h>
using namespace std;
int* func()
{
int *arr = new int[5];
return arr;
}
int main()
{
int *ip = func();
delete[] ip;
cout << endl;
return 0;
}
Key Points:
• Dynamic Allocation: Memory for the array is allocated inside the function using new.
• Return by Pointer: The function returns a pointer to the dynamically allocated array.
• Freeing Memory: It is essential to call delete[] in the calling function (i.e., in main())
to release the allocated memory when it is no longer needed.
The ternary operator is a shorthand way to write simple if-else statements. It is also known as
the conditional operator because it evaluates a condition and returns one of two values based on
whether the condition is true or false.
Syntax:
Example:
#include <bits/stdc++.h>
int main()
{
int x;
cin >> x;
return 0;
}
Key Points:
• Scenario: You need data structures (like arrays, lists, etc.) whose size is not fixed or known
in advance.
• Example: Creating an array where the size is determined by user input.
o In static memory allocation, arrays have a fixed size.
o With dynamic memory allocation, you can allocate memory based on the input
size, e.g., allocating memory for an array of n elements, where n is determined at
runtime.
• Scenario: You need to handle large amounts of data that exceed the capacity of stack
memory.
o Stack memory has limited size, and large allocations on the stack can lead to stack
overflow.
o Heap memory, managed via dynamic allocation, provides more space and allows
for handling larger data structures (like large arrays, matrices, etc.).
• Scenario: You need objects or data to persist beyond the scope of a function or block.
o Local variables are stored in the stack and are destroyed once the function call
ends.
o With dynamic allocation, the memory allocated in the heap can persist and be
accessed even after the function where it was allocated has returned.
• Scenario: Data structures like linked lists, trees, or graphs require dynamic memory
allocation because their size can grow or shrink as elements are added or removed.
o These structures are dynamic in nature, and memory must be allocated as nodes are
created and deallocated when nodes are deleted.
• Scenario: You want to resize a data structure like an array dynamically during the
execution of the program.
o In static memory allocation, arrays cannot be resized. However, using dynamic
memory allocation with realloc() (in C) or manually reallocating memory (in
C++), you can grow or shrink the size of an array during runtime.
• Scenario: When the exact amount of memory needed varies, dynamic memory allocation
allows you to allocate exactly the memory required, avoiding memory waste that can
happen with statically allocated, overestimated arrays or buffers.
o Example: You can allocate memory based on the exact size of a file being
processed, instead of pre-allocating a large buffer for potential file sizes.
7. Memory-Intensive Applications
• Scenario: When you need to implement custom memory management techniques (like
pooling or caching), dynamic memory allocation is essential.
o You can allocate memory only when required and deallocate it when not in use to
optimize the performance of your program.