结合可变分区管理的3种分配,最先分配算法,最优分配算法,最坏分配算法的一个代码
时间: 2023-11-02 17:20:30 浏览: 49
以下是结合可变分区管理的三种分配算法的代码实现,可以根据需要选择相应的算法:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义分区节点
struct node {
int start; // 分区起始地址
int size; // 分区大小
int status; // 分区状态,0表示空闲,1表示已分配
struct node *next; // 指向下一个节点的指针
};
// 初始化可变分区链表
struct node *initList(int start, int size) {
struct node *head = (struct node*)malloc(sizeof(struct node));
head->start = start;
head->size = size;
head->status = 0;
head->next = NULL;
return head;
}
// 输出可变分区链表
void printList(struct node *head) {
struct node *p = head;
while (p != NULL) {
printf("起始地址:%d,大小:%d,状态:%d\n", p->start, p->size, p->status);
p = p->next;
}
}
// 最先分配算法
void firstFit(struct node *head, int size) {
struct node *p = head;
while (p != NULL) {
if (p->status == 0 && p->size >= size) {
p->status = 1;
printf("已分配分区:起始地址为%d,大小为%d\n", p->start, size);
if (p->size > size) {
struct node *node = (struct node*)malloc(sizeof(struct node));
node->start = p->start + size;
node->size = p->size - size;
node->status = 0;
node->next = p->next;
p->next = node;
p->size = size;
}
return;
}
p = p->next;
}
printf("无法分配分区:没有足够的空闲内存\n");
}
// 最优分配算法
void bestFit(struct node *head, int size) {
struct node *p = head;
struct node *best = NULL;
while (p != NULL) {
if (p->status == 0 && p->size >= size) {
if (best == NULL || p->size < best->size) {
best = p;
}
}
p = p->next;
}
if (best != NULL) {
best->status = 1;
printf("已分配分区:起始地址为%d,大小为%d\n", best->start, size);
if (best->size > size) {
struct node *node = (struct node*)malloc(sizeof(struct node));
node->start = best->start + size;
node->size = best->size - size;
node->status = 0;
node->next = best->next;
best->next = node;
best->size = size;
}
} else {
printf("无法分配分区:没有足够的空闲内存\n");
}
}
// 最坏分配算法
void worstFit(struct node *head, int size) {
struct node *p = head;
struct node *worst = NULL;
while (p != NULL) {
if (p->status == 0 && p->size >= size) {
if (worst == NULL || p->size > worst->size) {
worst = p;
}
}
p = p->next;
}
if (worst != NULL) {
worst->status = 1;
printf("已分配分区:起始地址为%d,大小为%d\n", worst->start, size);
if (worst->size > size) {
struct node *node = (struct node*)malloc(sizeof(struct node));
node->start = worst->start + size;
node->size = worst->size - size;
node->status = 0;
node->next = worst->next;
worst->next = node;
worst->size = size;
}
} else {
printf("无法分配分区:没有足够的空闲内存\n");
}
}
int main() {
// 初始化可变分区链表
struct node *head = initList(0, 1024);
// 输出可变分区链表
printf("可变分区链表如下:\n");
printList(head);
// 分配内存
printf("执行最先分配算法:\n");
firstFit(head, 256);
printf("执行最优分配算法:\n");
bestFit(head, 512);
printf("执行最坏分配算法:\n");
worstFit(head, 128);
// 输出可变分区链表
printf("可变分区链表如下:\n");
printList(head);
return 0;
}
```