【数据结构】算法8.2 伙伴系统-分配

本文深入探讨了伙伴系统这一数据结构算法,主要讲解如何在内存管理中有效地分配和回收内存块,通过伙伴系统实现对大小为2的幂次的块进行高效管理,提升内存利用率。
摘要由CSDN通过智能技术生成
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW_SELF -2

#define M 3  //可利用空间总容量64K字的2的幂次,子表的个数为M+1 //书上为16

typedef int Status;
typedef int ElemType;
typedef struct WORD_b
{
    struct WORD_b *llink;  //指向前驱结点
    int tag;  //块标志,0:空闲,1:占用 
    int kval;  //块大小,值为2幂次K
    struct WORD_b *rlink;  //头部域,指向后继结点
}WORD_b,head;  //WORD:内存字类型,结点的第一个字也称为head
typedef struct HeadNode
{
    int nodes
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
伙伴系统是一种内存管理算法,它将可用内存块分成不同的大小类别,并将相邻的大小类别组合成伙伴对。当需要分配内存时,伙伴系统会寻找最小的大小类别,如果没有可用的内存块,则向更大的大小类别请求。当释放内存时,伙伴系统会检查它的伙伴是否也是空闲的,如果是,则将它们合并成更大的内存块。 以下是伙伴系统的C语言实现,使用了二叉树数据结构来管理内存块。 ``` #include <stdio.h> #include <stdlib.h> #include <math.h> #define MAXSIZE 1024 typedef struct node { int size; int status; // 0 for free, 1 for used struct node *left; // left child struct node *right; // right child } Node; Node *tree[MAXSIZE]; // binary tree // return the depth of the binary tree int depth(int size) { return (int) log2(size) + 1; } // initialize the binary tree with size and status void init(int size) { int d = depth(size); int i; for (i = 0; i < MAXSIZE; i++) { tree[i] = NULL; } tree[d - 1] = (Node *) malloc(sizeof(Node)); tree[d - 1]->size = size; tree[d - 1]->status = 0; tree[d - 1]->left = NULL; tree[d - 1]->right = NULL; } // allocate memory with size void *alloc(int size) { int d = depth(size); int i; for (i = d - 1; i < MAXSIZE; i++) { Node *p = tree[i]; while (p != NULL) { if (p->size == size && p->status == 0) { p->status = 1; return p; } else if (p->size >= size * 2 && p->status == 0) { p->left = (Node *) malloc(sizeof(Node)); p->left->size = p->size / 2; p->left->status = 0; p->left->left = NULL; p->left->right = NULL; p->right = (Node *) malloc(sizeof(Node)); p->right->size = p->size / 2; p->right->status = 0; p->right->left = NULL; p->right->right = NULL; p->status = 1; return alloc(size); } p = p->right; } } return NULL; } // free memory with pointer void free_mem(void *p) { Node *node = (Node *) p; node->status = 0; while (node != NULL) { if (node->left->status == 0 && node->right->status == 0) { node->left = NULL; node->right = NULL; node = node->parent; } else { break; } } } int main() { init(1024); void *p1 = alloc(128); void *p2 = alloc(256); void *p3 = alloc(512); free_mem(p1); void *p4 = alloc(128); return 0; } ``` 这个实现使用了一个全局数组`tree`来存储二叉树节点。`init`函数用于初始化二叉树,`alloc`函数用于分配内存,`free_mem`函数用于释放内存。在`alloc`函数中,我们首先找到最小的可用内存块,如果没有可用的内存块,则向更大的内存块请求。如果分配成功,则将该内存块的状态设置为已使用,否则返回空指针。在`free_mem`函数中,我们将该内存块的状态设置为未使用,并检查它的伙伴是否也是空闲的,如果是,则将它们合并成更大的内存块。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值