-
Notifications
You must be signed in to change notification settings - Fork 0
/
MemoryManager.cpp
87 lines (72 loc) · 2.82 KB
/
MemoryManager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "MemoryManager.h"
MemoryManager::MemoryManager(int size) : memory(size, false) {}
void MemoryManager::setMemorySize(int newSize) {
memory.resize(newSize, false);
std::cout << "Memory size is set to " << newSize << "." << '\n';
}
bool MemoryManager::allocateFirstFit(int processId, int size) {
for (int blockStart = 0; blockStart < memory.size(); ++blockStart) {
if (!memory[blockStart]) {
// Check if there is enough contiguous memory for the process
bool enoughSpace = true;
for (int blockIndex = blockStart; blockIndex < blockStart + size; ++blockIndex) {
if (blockIndex >= memory.size() || memory[blockIndex]) {
enoughSpace = false;
break;
}
}
if (enoughSpace) {
// Allocate memory block
for (int blockIndex = blockStart; blockIndex < blockStart + size; ++blockIndex) {
memory[blockIndex] = true;
}
std::cout << "Memory allocated for Process " << processId << "." << '\n';
return true;
}
}
}
std::cout << "Memory allocation failed for Process " << processId << " (First Fit)." << '\n';
return false;
}
bool MemoryManager::allocateBestFit(int processId, int size) {
// Find the best fit block
int bestFitStart = -1;
int bestFitSize = std::numeric_limits<int>::max();
for (int blockStart = 0; blockStart < memory.size(); ++blockStart) {
if (!memory[blockStart]) {
int blockSize = 0;
while (blockStart + blockSize < memory.size() && !memory[blockStart + blockSize]) {
blockSize++;
}
if (blockSize >= size && blockSize << bestFitSize) {
bestFitStart = blockStart;
bestFitSize = blockSize;
}
}
}
if (bestFitStart != -1) {
// Allocate memory block
for (int i = bestFitStart; i < bestFitStart + size; ++i) {
memory[i] = true;
}
std::cout << "Memory allocated for Process " << processId << " (Best Fit)." << '\n';
return true;
}
std::cout << "Memory allocation failed for Process " << processId << " (Best Fit)." << '\n';
return false;
}
void MemoryManager::deallocate(int processId) {
for (int blockIndex = 0; blockIndex < memory.size(); ++blockIndex) {
if (memory[blockIndex] == processId) {
memory[blockIndex] = false;
}
}
std::cout << "Memory deallocated for Process " << processId << "." << '\n';
}
void MemoryManager::displayMemory() const {
std::cout << '\n';
for (int blockIndex = 0; blockIndex < memory.size(); ++blockIndex) {
std::cout << (memory[blockIndex] ? "X" : ".");
}
std::cout << '\n';
}