最坏适应算法的c语言实现代码
时间: 2023-07-27 16:07:28 浏览: 69
以下是最坏适应算法的C语言实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 1024
// 内存块结构体,用于表示空闲内存块
typedef struct MemoryBlock {
int startAddr; // 内存块起始地址
int size; // 内存块大小
struct MemoryBlock *next; // 指向下一个内存块
} MemoryBlock;
// 全局变量,用于存储空闲内存块链表的头节点
MemoryBlock *freeMemory = NULL;
// 初始化内存块链表
void initFreeMemory() {
freeMemory = (MemoryBlock*)malloc(sizeof(MemoryBlock));
freeMemory->startAddr = 0;
freeMemory->size = MAX_SIZE;
freeMemory->next = NULL;
}
// 分配内存空间
int allocateMemory(int size) {
MemoryBlock *p = freeMemory;
MemoryBlock *prev = NULL;
MemoryBlock *largestBlock = NULL;
int largestBlockSize = -1;
// 遍历空闲内存块链表,找到最大的可以满足当前请求的块
while (p != NULL) {
if (p->size >= size && p->size > largestBlockSize) {
largestBlock = p;
largestBlockSize = p->size;
}
prev = p;
p = p->next;
}
// 找到符合要求的内存块
if (largestBlock != NULL) {
int startAddr = largestBlock->startAddr;
int remainingSize = largestBlock->size - size;
// 更新空闲内存块链表
if (remainingSize > 0) {
MemoryBlock *newBlock = (MemoryBlock*)malloc(sizeof(MemoryBlock));
newBlock->startAddr = startAddr + size;
newBlock->size = remainingSize;
newBlock->next = largestBlock->next;
if (prev == NULL) {
freeMemory = newBlock;
} else {
prev->next = newBlock;
}
} else {
if (prev == NULL) {
freeMemory = largestBlock->next;
} else {
prev->next = largestBlock->next;
}
}
// 返回分配的内存块起始地址
return startAddr;
}
// 没有符合要求的内存块,返回-1表示分配失败
return -1;
}
// 释放内存空间
void freeMemoryBlock(int startAddr, int size) {
MemoryBlock *p = freeMemory;
MemoryBlock *prev = NULL;
// 遍历空闲内存块链表,找到可以插入该内存块的位置
while (p != NULL && p->startAddr < startAddr) {
prev = p;
p = p->next;
}
// 将该内存块插入链表中
MemoryBlock *newBlock = (MemoryBlock*)malloc(sizeof(MemoryBlock));
newBlock->startAddr = startAddr;
newBlock->size = size;
newBlock->next = p;
if (prev == NULL) {
freeMemory = newBlock;
} else {
prev->next = newBlock;
}
}
// 打印空闲内存块链表
void printFreeMemory() {
MemoryBlock *p = freeMemory;
printf("Free Memory:\n");
while (p != NULL) {
printf("Start Address: %d, Size: %d\n", p->startAddr, p->size);
p = p->next;
}
}
int main() {
initFreeMemory();
// 分配内存空间
int addr1 = allocateMemory(256);
int addr2 = allocateMemory(512);
int addr3 = allocateMemory(128);
printFreeMemory();
// 释放内存空间
freeMemoryBlock(addr2, 512);
printFreeMemory();
return 0;
}
```
在这个示例程序中,我们使用链表来维护空闲内存块,每次分配内存空间时,我们遍历链表,找到最大的可以满足当前请求的块,并将其分配给进程。每次释放内存空间时,我们将该内存块插入链表中,并尝试合并相邻的空闲内存块。
阅读全文