资源简介
内存分配算法代码模拟。包含 首次适应算法(First Fit) 最佳适应算法(Best Fit)最差适应算法(Worst Fit)伙伴算法(buddy)
https://blog.csdn.net/GreyBtfly/article/details/84646981
代码片段和文件信息
#include
using namespace std;
/*进程分配内存块链表的首指针*/
struct allocated_block *allocated_block_head = NULL;
#define PROCESS_NAME_LEN 32 /*进程名长度*/
#define MIN_SLICE 10 /*最小碎片的大小*/
#define DEFAULT_MEM_SIZE 1024 /*内存大小*/
#define DEFAULT_MEM_START 0 /*起始位置*/
/* 内存分配算法 */
#define MA_FF 1 //first fit
#define MA_BF 2
#define MA_WF 3
#define Buddy 4 //伙伴算法
/*描述每一个空闲块的数据结构*/
struct free_block_type{
int size;
int start_addr;
struct free_block_type *next;
};
typedef struct free_block_type FB;
/*指向内存中空闲块链表的首指针*/
struct free_block_type *free_block;//此处尽量按内存地址顺序排列 ,
/*每个进程分配到的内存块的描述*/
struct allocated_block{
int pid; int size;
int start_addr;
char process_name[PROCESS_NAME_LEN];
struct allocated_block *next;
};
typedef struct allocated_block allocated_block_type;
//buddy
typedef struct b_free_block_type
{
int size;
free_block_type *list;
b_free_block_type *next;
}b_free_block_type;
b_free_block_type *b_free_block=NULL;//空的时候要设置为NULL
//end of buddy
typedef struct allocated_block AB;
int mem_size=DEFAULT_MEM_SIZE; /*内存大小*/
int ma_algorithm = Buddy; /*当前分配算法*/ //------------------------>>>>>>>>>
static int pid = 0; /*初始pid*/
int flag = 0; /*设置内存大小标志*/
//init_free_block(int mem_size);
int display_mem_usage();
int b_creat_free_blocks(free_block_type *ab);
int rearrange_Buddy();
int rearrange(int algorithm);
int allocate_mem(struct allocated_block *ab);
int free_mem(struct allocated_block *ab);
int dispose(struct allocated_block *free_ab);
int disfree(FB *free_ab);
void free_f();
void free_b();
/*初始化空闲块,默认为一块,可以指定大小及起始地址*/
struct free_block_type* init_free_block(int mem_size)
{
free_f();
free_b();
struct free_block_type *fb;
fb=(struct free_block_type *)malloc(sizeof(struct free_block_type));
if(fb==NULL){
printf(“Error.\n“);
getchar();
return NULL;
}
fb->size = mem_size;
fb->start_addr = DEFAULT_MEM_START;
fb->next = NULL;
free_block=(struct free_block_type *)malloc(sizeof(struct free_block_type));
*free_block=*fb; //free_block供rearrange_Buddy使用,会被销毁
rearrange_Buddy();//初始化buddy算法
return fb; //会在main中重新赋值free_block
}
/*显示菜单*/
void display_menu(){
printf(“\n“);
printf(“1 - Set memory size (default=%d)\n“ DEFAULT_MEM_SIZE);
printf(“2 - Select memory allocation algorithm\n“);
printf(“3 - New process \n“);
printf(“4 - Terminate a process \n“);
printf(“5 - Display memory usage \n“);
printf(“0 - Exit\n“);
}
/*设置内存的大小*/
int set_mem_size(){ //只能设置一次 清除现有所有链表,重新分配
int size;
if(flag!=0){ //防止重复设置
printf(“Cannot set memory size again\n“);
return 0;
}
printf(“Total memory size =“);
scanf(“%d“ &size);
if(size>0) {
mem_size = size;
// free_block->size = mem_size;
- 上一篇:OpenCv背景差分228299
- 下一篇:c++usb端口访问
评论
共有 条评论