Memory Management
Memory Management Strategies for Character Arrays
Manual Memory Management
class CharArrayManager {
private:
char* data;
size_t size;
public:
// Constructor
CharArrayManager(size_t length) {
data = new char[length];
size = length;
}
// Destructor
~CharArrayManager() {
delete[] data;
}
// Copy constructor
CharArrayManager(const CharArrayManager& other) {
data = new char[other.size];
memcpy(data, other.data, other.size);
size = other.size;
}
};
Memory Management Techniques
Technique |
Description |
Pros |
Cons |
Manual Management |
Direct new/delete |
Full control |
Error-prone |
Smart Pointers |
Automatic cleanup |
Safe |
Slight overhead |
RAII |
Resource acquisition |
Exception safe |
Learning curve |
Smart Pointer Usage
#include <memory>
class SafeCharArray {
private:
std::unique_ptr<char[]> buffer;
size_t length;
public:
SafeCharArray(size_t size) {
buffer = std::make_unique<char[]>(size);
length = size;
}
char* get() { return buffer.get(); }
};
Memory Lifecycle Management
graph TD
A[Allocation] --> B[Initialization]
B --> C{Usage}
C -->|Read| D[Access Data]
C -->|Write| E[Modify Data]
C --> F[Cleanup]
F --> G[Deallocation]
Common Memory Management Challenges
Memory Leaks
void problematicFunction() {
char* leaked = new char[100];
// No delete[] - memory leak occurs
}
Safe Alternative
void safeFunction() {
std::vector<char> safeBuffer(100);
// Automatic memory management
}
Advanced Memory Management
Custom Memory Allocator
class CustomCharAllocator {
public:
char* allocate(size_t size) {
return new char[size];
}
void deallocate(char* ptr) {
delete[] ptr;
}
};
Best Practices
- Use RAII principles
- Prefer smart pointers
- Avoid raw pointer manipulation
- Use standard library containers
- Implement proper destructor/cleanup methods
Exception-Safe Memory Handling
class ExceptionSafeCharArray {
private:
std::unique_ptr<char[]> data;
public:
ExceptionSafeCharArray(size_t size) {
try {
data = std::make_unique<char[]>(size);
} catch (const std::bad_alloc& e) {
// Handle allocation failure
std::cerr << "Memory allocation failed" << std::endl;
}
}
};
- Minimize dynamic allocations
- Use stack allocation when possible
- Leverage move semantics
- Avoid frequent memory reallocations
Modern C++ Recommendations
Prefer Standard Containers
#include <string>
#include <vector>
void modernApproach() {
std::string dynamicString = "LabEx Modern Approach";
std::vector<char> flexibleBuffer(100);
}
By mastering these memory management techniques, developers can write more robust, efficient, and safe C++ code when working with character arrays.