可变分区管理的3种分配,最先分配算法,最优分配算法,最坏分配算法代码
时间: 2023-11-02 09:20:30 浏览: 41
下面是可变分区管理的三种分配算法的简单代码实现,供参考:
最先分配算法:
```c
struct node {
int start; // 分区起始地址
int size; // 分区大小
int status; // 分区状态,0表示空闲,1表示已分配
struct node *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");
}
```
最优分配算法:
```c
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");
}
}
```
最坏分配算法:
```c
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");
}
}
```