Object Oriented ProgrammingUnit 37 min read
Storage Classes & Memory Management: Scope, Lifetime, Allocation
Unit 3 of Object Oriented Programming: Covers storage classes (auto, static, register, extern, mutable), memory management (stack vs. heap, new/delete, dynamic allocation), and their impact on program behavior, efficiency, and resource usage in C++.
Core Concepts
1. Storage Classes in C++
Storage classes define scope, lifetime, and visibility of variables/functions. There are five storage classes:
| Storage Class | Keyword | Scope | Lifetime | Visibility | Example Use Case |
|---|---|---|---|---|---|
| Automatic | auto |
Block-level | Exists until block ends | Local to block | Loop counters, temporary variables |
| Static | static |
Block-level or global | Entire program run | Local or global | Global constants, persistent state |
| Register | register |
Block-level | Exists until block ends | Local to block | High-frequency variables (rarely used) |
| Extern | extern |
Global | Entire program run | Across files | Shared variables in multiple files |
| Mutable | mutable |
Class member | Object lifetime | Class-level | Thread-safe flags in const methods |
Visual: Scope and Lifetime
classDiagram
class Auto {
+scope: Block
+lifetime: Until block ends
}
class Static {
+scope: Block/Global
+lifetime: Entire program
}
class Register {
+scope: Block
+lifetime: Until block ends
}
class Extern {
+scope: Global
+lifetime: Entire program
}
class Mutable {
+scope: Class member
+lifetime: Object lifetime
}
Auto --> "Short-lived" Block
Static --> "Persistent" Global
Extern --> "Shared" File2. Memory Management
A. Static vs. Dynamic Memory Allocation
| Feature | Static Allocation | Dynamic Allocation |
|---|---|---|
| Memory Location | Stack | Heap |
| Lifetime | Fixed (compile-time) | Runtime (until delete) |
| Flexibility | Limited (size fixed) | Flexible (resizeable) |
| Speed | Faster (pre-allocated) | Slower (runtime overhead) |
| Use Case | Small, fixed-size data (e.g., arrays) | Large, variable-size data (e.g., linked lists) |
Visual: Stack vs. Heap
B. Dynamic Memory Allocation with new and delete
new: Allocates memory on the heap and returns a pointer.delete: Frees allocated memory to prevent memory leaks.- Example:
int* ptr = new int(10); // Allocates memory for an int cout << *ptr; // Output: 10 delete ptr; // Frees memory ptr = nullptr; // Good practice
Visual: Memory Allocation Steps
sequenceDiagram
participant Program as Program
participant Heap as Heap
Program->>Heap: ptr = new int(10)
Heap-->>Program: Returns address
Program->>Heap: delete ptr
Heap-->>Program: Memory freedWorked Example: Book Inventory System
Problem: A bookshop tracks books (title, author, price, stock). Use dynamic memory to manage variable inventory.
Solution Code
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title, author;
double price;
int stock;
public:
Book(string t, string a, double p, int s)
: title(t), author(a), price(p), stock(s) {}
void display() {
cout << "Title: " << title << "\nAuthor: " << author
<< "\nPrice: $" << price << "\nStock: " << stock << endl;
}
};
int main() {
// Dynamic allocation for variable inventory
Book* inventory[100]; // Array of pointers
int count = 0;
// Add books dynamically
inventory[count++] = new Book("C++ for Beginners", "John Doe", 49.99, 50);
inventory[count++] = new Book("OOP Concepts", "Jane Smith", 59.99, 30);
// Display inventory
for (int i = 0; i < count; i++) {
inventory[i]->display();
delete inventory[i]; // Free memory
}
return 0;
}
Visual: Memory After Allocation
In the Real World
eSewa (Nepal):
- Uses dynamic memory to handle variable transaction sizes (e.g., electricity bills, fines).
- Example: When a user pays a bill, eSewa allocates memory for the transaction record dynamically and frees it after processing.
Khalti (Mobile Payments):
- Employs static storage for global transaction logs (e.g.,
static int totalTransactions). - Uses heap allocation for large payment records (e.g., merchant transactions).
- Employs static storage for global transaction logs (e.g.,
Daraz (E-commerce):
- Stack memory for short-lived operations (e.g., cart items during checkout).
- Heap memory for user accounts (stored dynamically as users join/leave).
Worked Example Tie-In:
- If Daraz used static allocation for all orders, it would crash when exceeding pre-defined limits (e.g., 1000 orders). Instead, it uses dynamic arrays (
vectorin C++) to scale.
Key Algorithms: Memory Management
1. Detecting Memory Leaks (Manual Check)
flowchart TD
A["Start"] --> B{"Is pointer null?"}
B -->|"Yes"| C["No leak"]
B -->|"No"| D["Check if deleted"]
D -->|"Deleted"| C
D -->|"Not Deleted"| E["Memory Leak Detected"]Code Example:
void checkLeak(int* ptr) {
if (ptr != nullptr) {
cout << "Warning: Potential leak!" << endl;
}
}
Exam Tip
Storage Classes:
- Remember
staticvariables retain value between function calls. externis used for cross-file variable sharing (e.g., global constants).
- Remember
Dynamic Memory:
- Always pair
newwithdeleteto avoid leaks. - Use smart pointers (
unique_ptr,shared_ptr) in modern C++ to automate memory management.
- Always pair
Common Pitfalls:
- Dangling pointers: Accessing freed memory (e.g.,
delete ptr; cout << *ptr;). - Double deletion: Calling
deletetwice on the same pointer.
- Dangling pointers: Accessing freed memory (e.g.,
Exam Questions Likely To Ask:
- Define scope/lifetime of storage classes.
- Write a program using
new/deletefor dynamic arrays. - Explain memory leaks and how to prevent them.
Visual Summary
Based on the TU BSc CSIT syllabus for Object Oriented Programming (CSC166), unit 3.
Discussion
Loading…