Memory allocation and recovery experiments

Memory allocation and recovery

Beijing Normal University, Zhuhai

Purpose

1. By using bitmap or free list, track memory usage, simulate and evaluate different memory allocation algorithms;

2. Familiar with memory allocation and recycling management process.

Experimental requirements

1. It is required to write and debug a memory allocation and recovery simulation program in a programming language you are familiar with; it is required to test in the main function.

2. The experimental report must include: design ideas, data definitions (including detailed descriptions), processing procedures (detailed algorithm descriptions and algorithm flow charts), source codes, operating results, experience, etc.

3. Must simulate at least 2 of the 4 memory allocation algorithms: first fit, next fit, best fit and worst fit.

4. It is necessary to display the situation of the free partition chain after each allocation and recovery, as well as the memory usage diagram.

5. (Optional:) Calculate two performance parameters: the number of fragments (the number of free areas less than 2 units), and the number of free area comparisons (searches) to complete a memory allocation, that is, to complete a certain number of comparisons after several comparisons. requested memory allocation.

Experimental content

Suppose the memory capacity is 256KB, and it is divided into 1KB blocks, that is, each memory unit is 1KB. The memory required by a process is 3 to 10 units. At the same time, it is assumed that the size of the memory required by a job does not change during the running process.

The simulation includes 3 parts:
1. Realize a specific memory allocation algorithm
2. Realize memory recovery simulation
3. Statistics on the number of fragments corresponding to each memory allocation strategy (optional)

Experimental procedure

1. Determine the memory space allocation table

1) Data item design
2) Storage structure determination

The memory space allocation table adopts the data form of a doubly linked list

The data structure of the allocated space block is:
Forward pointer: before the initial value is -1, pointing to the
position of the previous node of the node The position of the process block in memory: strtLocation indicates the location information of the memory block
Process block id: the flag is Occupied memory block
Space size: size indicates the size of the occupied memory
Backward pointer: The initial value of next is -1, indicating the next node position of the node

The data structure of the free block:
Forward pointer: before the initial value is -1, pointing to the position of the previous free block of the free block The
position of the free block in memory: strtLocation indicates the position information
space of the free block: size indicates the free space The size of
the backward pointer: the initial value of next is -1, indicating the position of the next free block of the node

Job block linked list data structure

insert image description here

Free block list data structure

insert image description here

2. Use two algorithms to complete the allocation and recovery of memory space

1) Algorithm analysis
2) Algorithm flowchart drawing
3) Coding
4) Debugging
3. Write the main function to test the work done.

allocation recovery algorithm

1. First Fit Algorithm FirstFit——The free list is linked in the order of increasing address, and the free area in the low address part of the memory is allocated first. High address and large free area can be reserved.

2. Cyclic Adaptation Algorithm NextFit——Search from the next free partition of the free partition found last time. A start query pointer shall be set. This algorithm distributes free partitions more evenly.

3. Best Fit Algorithm BestFit—The free linked list is linked in the order of increasing partition size, and the smallest free area in the memory that meets the conditions is allocated first.

4. Worst Fit Algorithm WorstFit—The free list is linked in descending order of partition size, and the largest free area in the memory is allocated first.

accomplish

1. First adaptation algorithm

1. Core idea

When allocating a job block, search according to the position of the free block in the memory until a memory block of suitable size is found (the size of the free block is greater than or equal to the size of the job block)

2. Difficulty analysis

When reclaiming a memory block, the memory list will have the following three situations:
(1) There are adjacent free blocks on the left and right sides of the reclaimed block;
(2) There are adjacent free blocks on the left or right of the reclaimed block ;
(3) There are no adjacent recycling blocks on the left and right of the recycling block;

3. Problem solving

Case (1): merge three free blocks;
case (2): merge two adjacent free blocks;
case (3): add free blocks to the free list;

4. Algorithm flow chart

Assign job blocks

insert image description here

Recycle

insert image description here

Code

ProcessNode class
//Initialize job blocks and free blocks

package com.it.bnuz.yzy;

public class ProcessNode {
    
    
    private int id;
    private int size;

    public ProcessNode(int id, int size) {
    
    
        this.id = id;
        this.size = size;
    }

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public int getSize() {
    
    
        return size;
    }

    public void setSize(int size) {
    
    
        this.size = size;
    }
}

UseNode class:
//job block

package com.it.bnuz.yzy;

public class UseNode implements Comparable<UseNode> {
    
    
    private int before = -1;//初始为-1,-1表示表头
    private int startLocation;
    private int id;
    private int size;
    private int next = -1;//初始为-1,-1表示表尾

    public UseNode(int id, int size) {
    
    
        this.id = id;
        this.size = size;
    }

    public int getBefore() {
    
    
        return this.before;
    }

    public void setBefore(int before) {
    
    
        this.before = before;
    }

    public int getStartLocation() {
    
    
        return this.startLocation;
    }

    public void setStartLocation(int startLocation) {
    
    
        this.startLocation = startLocation;
    }

    public int getId() {
    
    
        return this.id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public int getSize() {
    
    
        return this.size;
    }

    public void setSize(int size) {
    
    
        this.size = size;
    }

    public int getNext() {
    
     return this.next; }

    public void setNext(int next) {
    
    
        this.next = next;
    }

    public int compareTo(UseNode o) {
    
    
        return this.startLocation - o.getStartLocation();
    }

    public String toString() {
    
    
        String str = "[before:" + this.before + " startLocation:" + this.startLocation + " id:" + this.id + " size:" + this.size + " next:" + this.next + "]";
        return str;
    }
}

FreeNode class:
// free block

package com.it.bnuz.yzy;

public class FreeNode implements Comparable<FreeNode> {
    
    
    private int before = -1;
    private int startLocation;
    private int size;
    private int next = -1;

    public FreeNode(int size) {
    
    
        this.size = size;
    }

    public int getBefore() {
    
    
        return before;
    }

    public void setBefore(int before) {
    
    
        this.before = before;
    }

    public int getStartLocation() {
    
    
        return startLocation;
    }

    public void setStartLocation(int startLocation) {
    
    
        this.startLocation = startLocation;
    }

    public int getSize() {
    
    
        return size;
    }

    public void setSize(int size) {
    
    
        this.size = size;
    }

    public int getNext() {
    
    
        return next;
    }

    public void setNext(int next) {
    
    
        this.next = next;
    }

    @Override
    public int compareTo(FreeNode o) {
    
    
        return this.startLocation - o.getStartLocation();
    }

    @Override
    public String toString() {
    
    
        String str = "[before:"+before+" startLocation:"+startLocation+" size:"+size+" next:"+next+"]";
        return str;
    }
}

memory map

private String[] memory_space = new String[256];

The memory situation in the initial state:
//The memory space is a rectangular space of 16 * 16, the size is 256k, and one unit represents 1k
//0 represents the free area

insert image description here

Job linked list:

private List<UseNode> useSpaceList = new ArrayList<>();

Free list:

private List<FreeNode> freeSpaceList = new ArrayList<>();

FirstFit Allocation Algorithm:

/*
    *FirstFit首次适应算法 分配算法
    * */
    void FirstFit_distribution(ProcessNode p){
    
    
        UseNode useNode = new UseNode(p.getId(),p.getSize());
        int size = p.getSize();
        int count = 0;
        for(int i = 0; i < freeSpaceList.size();i++){
    
    //循环寻找是否有合适大小的空闲块
            count++;
            if(size <= freeSpaceList.get(i).getSize()){
    
    
                //先处理空闲快链表
                FreeNode freeNode = freeSpaceList.get(i);
                useNode.setStartLocation(freeNode.getStartLocation());//插入进的占用块结点的起始位置为这个空闲块的起始位置

                if(size < freeNode.getSize()){
    
    //插入块的大小小于该空闲块的大小时,该空闲块的起始位置发生改变,大小发生改变
                    freeSpaceList.get(i).setStartLocation(freeNode.getStartLocation() + p.getSize());
                    freeSpaceList.get(i).setSize(freeNode.getSize() - p.getSize());
                }
                else{
    
    //如果插入块的大小和该空闲块的大小相同,从链表中删除这个空闲块
                    if(i == 0){
    
    
                        freeSpaceList.get(i+1).setBefore(-1);//如果这个空闲块是表头,那么将下一个空闲块的before置为-1;
                    }
                    else{
    
    
                        freeSpaceList.get(i-1).setNext(freeSpaceList.get(i).getNext());
                        freeSpaceList.get(i+1).setBefore(freeSpaceList.get(i).getBefore());
                    }
                }
                //在内存中显示分配情况
                for(int j = useNode.getStartLocation();j < useNode.getStartLocation() + useNode.getSize();j++){
    
    
                    if(j == useNode.getStartLocation()){
    
    
                        memory_space[j] = ""+useNode.getId()+" ";
                    }
                    else{
    
    
                        memory_space[j] = "+ ";
                    }
                }
                showMemory();
                //对分配列表进行操作
                firstFit_add(useNode);
                showUseSpaceList();
                showFreeSpaceList();
                return;
            }
            else {
    
    
                continue;
            }
        }
        if(count == freeSpaceList.size()){
    
    
            System.out.println("没有合适的空闲块,插入失败");
            return;
        }
    }

In the allocation algorithm, the function for operating the job list:
firstFit_add(UseNode useNode)
When inserting the job list, the position of the job list is divided into three situations:
1. Header
2. Table
3. Footer

/*
    * firstFit加入分配空间
    * */
    private  void firstFit_add(UseNode useNode){
    
    
        //操作占用块链表
        useSpaceList.add(useNode);
        if(useSpaceList.size() > 1){
    
    
            useSpaceList.sort(UseNode::compareTo);//通过起始地址号进行排序,模拟插入链表
            for(int k = 0;k < useSpaceList.size();k++){
    
    
                if(useNode.getId() == useSpaceList.get(k).getId()){
    
    
                    if(k == 0){
    
    
                        useSpaceList.get(k).setNext(useSpaceList.get(k+1).getStartLocation());//如果该占用块插到表头,将next指向源列表的表头起始地址
                        useSpaceList.get(k+1).setBefore(0);//将原表头的before指向表头
                    }
                    else if(k == useSpaceList.size()-1){
    
    
                        useSpaceList.get(k).setBefore(useSpaceList.get(k-1).getStartLocation());
                        useSpaceList.get(k-1).setNext(useSpaceList.get(k).getStartLocation());
                    }
                    else{
    
    
                        useSpaceList.get(k).setBefore(useSpaceList.get(k-1).getStartLocation());
                        useSpaceList.get(k).setNext(useSpaceList.get(k+1).getStartLocation());

                        useSpaceList.get(k-1).setNext(useSpaceList.get(k).getStartLocation());
                        useSpaceList.get(k+1).setBefore(useSpaceList.get(k).getStartLocation());
                    }
                }
            }
        }
    }

FirstFitRecycling

/*
    * firstFit首次适应算法,内存空间的释放
    * 根据分配链表查找到要释放的内存空间地址
    * 在空闲内存链表中添加空闲块
    * */
    public void firstFit_free(int id){
    
    
        //查找该块的内存块
        UseNode free_node = find_useNode(id);
        if(free_node != null){
    
    
            useSpaceList.remove(free_node);
            FreeNode freeNode = new FreeNode(free_node.getSize());
            freeNode.setStartLocation(free_node.getStartLocation());
            freeSpaceList.add(freeNode);
            freeSpaceList.sort(FreeNode::compareTo);
            for(int i = 0;i < freeSpaceList.size();i++){
    
    
                if(freeSpaceList.get(i).getStartLocation() == freeNode.getStartLocation()){
    
    
                    if(i == 0){
    
    //如果该空闲块为链表的表头
                        if((freeNode.getStartLocation() + freeNode.getSize()) == freeSpaceList.get(i+1).getStartLocation()){
    
    //如果两个空闲块相邻,拓展为一块
                            freeSpaceList.get(i).setSize(freeNode.getSize() + freeSpaceList.get(i).getSize());//合并两个空闲块
                            if(freeSpaceList.get(i+1).getNext() == -1){
    
    //如果相邻块是最后一个空闲块
                                freeSpaceList.remove(freeSpaceList.get(i+1));//将相邻空闲块删除
                                setFreeSpace(freeSpaceList.get(i).getStartLocation(),freeSpaceList.get(i).getSize());
                                break;
                            }
                            else{
    
    
                                freeSpaceList.get(i).setNext(freeSpaceList.get(i+1).getNext());//将空闲块的Next指向相邻块的下一个空闲块
                                freeSpaceList.get(i+2).setBefore(freeNode.getStartLocation());//将相邻块的下一个空闲块的before指向该空闲块
                                freeSpaceList.remove(freeSpaceList.get(i+1));
                                setFreeSpace(freeSpaceList.get(i).getStartLocation(),freeSpaceList.get(i).getSize());
                                break;
                            }
                        }
                        else{
    
    //如果两个空闲块不相邻
                            freeSpaceList.get(i).setNext(freeSpaceList.get(i+1).getStartLocation());
                            freeSpaceList.get(i+1).setBefore(freeSpaceList.get(i).getStartLocation());
                            setFreeSpace(freeSpaceList.get(i).getStartLocation(),freeSpaceList.get(i).getSize());
                        }
                    }
                    else if(i == (freeSpaceList.size() - 1)){
    
    //如果该空闲块位于链表表尾
                        FreeNode beforeNode = freeSpaceList.get(i-1);//空闲快的的前结点
                        if((beforeNode.getStartLocation() + beforeNode.getSize()) == free_node.getStartLocation()){
    
    //如果两个空闲块相邻
                            freeSpaceList.get(i-1).setSize(beforeNode.getSize() + freeNode.getSize());//合并
                            freeSpaceList.remove(freeNode);
                            setFreeSpace(freeNode.getStartLocation(),freeNode.getSize());
                            break;
                        }
                    }
                    else{
    
    //该空闲块在表中
                        FreeNode beforeNode = freeSpaceList.get(i-1);
                        FreeNode nextNode = freeSpaceList.get(i+1);
                        //分三种情况讨论:三个空闲块都相邻;只与左或右节点相邻;都不相邻
                        //都相邻
                        if((beforeNode.getStartLocation() + beforeNode.getSize() == freeNode.getStartLocation()) && (freeNode.getStartLocation() + freeNode.getSize() == nextNode.getStartLocation())){
    
    
                            freeSpaceList.get(i-1).setSize(beforeNode.getSize() + freeNode.getSize() + nextNode.getSize());
                            freeSpaceList.get(i-1).setNext(nextNode.getNext());
                            freeSpaceList.remove(freeNode);
                            freeSpaceList.remove(nextNode);
                            setFreeSpace(freeNode.getStartLocation(),freeNode.getSize());
                            break;
                        }
                        //与左相邻
                        else if(beforeNode.getStartLocation() + beforeNode.getSize() == freeNode.getStartLocation()){
    
    
                            freeSpaceList.get(i-1).setSize(beforeNode.getSize()+freeNode.getSize());
                            setFreeSpace(freeNode.getStartLocation(),freeNode.getSize());
                            break;
                        }
                        //与右相邻
                        else if(freeNode.getStartLocation() + freeNode.getSize() == nextNode.getStartLocation()){
    
    
                            freeSpaceList.get(i).setSize(freeNode.getSize()+nextNode.getSize());
                            freeSpaceList.get(i).setBefore(nextNode.getBefore());
                            freeSpaceList.get(i).setNext(nextNode.getNext());
                            freeSpaceList.remove(nextNode);
                            setFreeSpace(freeNode.getStartLocation(),freeNode.getSize());
                            break;
                        }
                        //都不相邻
                        else{
    
    
                            freeSpaceList.get(i).setBefore(beforeNode.getStartLocation());
                            freeSpaceList.get(i).setNext(nextNode.getStartLocation());
                            setFreeSpace(freeNode.getStartLocation(),freeNode.getSize());
                            break;
                        }
                    }
                }
            }
            showMemory();
            showUseSpaceList();
            showFreeSpaceList();
        }
    }

Query the information function of the recycling block and return a UseNode object

/*
    * 通过分配链表useSpaceList查询内存块,返回该内存快的信息
    * */
    private UseNode find_useNode(int id){
    
    
        for(int i = 0;i < useSpaceList.size();i++){
    
    
            if(useSpaceList.get(i).getId() == id){
    
    
                if(useSpaceList.size() > 1){
    
    
                    if(i == useSpaceList.size()-1){
    
    
                        useSpaceList.get(i-1).setNext(-1);
                    }
                    else if(i == 0){
    
    
                        useSpaceList.get(i+1).setBefore(-1);
                    }
                    else {
    
    
                        useSpaceList.get(i-1).setNext(useSpaceList.get(i).getNext());
                        useSpaceList.get(i+1).setBefore(useSpaceList.get(i).getBefore());
                    }
                }
                return useSpaceList.get(i);
            }
        }
        return null;
    }

The results show

Assign job blocks

Please enter id: 1
Please enter occupied memory size: 35

Please enter id: 2
Please enter occupied memory size: 85

Please enter id: 3
Please enter occupied memory size: 9

Please enter id: 4
Please enter the occupied memory size: 21

Please enter id: 5
Please enter the occupied memory size: 19

Please enter id: 6
Please enter occupied memory size: 23

Please enter id: 7
Please enter occupied memory size: 15

Please enter id: 8
Please enter occupied memory size: 3

Please enter id: 9
Please enter the occupied memory size: 6

The memory situation after allocation:

insert image description here

Assigned job block linked list:

insert image description here

Free fast linked list after allocation:

insert image description here

Recycle

Recycle the job block with id=5

insert image description here

Job linked list:

insert image description here

Free block list:

insert image description here

The case where there are free blocks on both sides:

before recycling

insert image description here

after recycling

insert image description here

job block list

insert image description here

free fast linked list

insert image description here

reinsert

insert image description here
insert image description here

2. Cyclic Adaptation Algorithm

1. Core idea

Mark in the free block list. When inserting a job block, search for a suitable free block to insert from the next free block of the free block marked last time.

2. Algorithm flow chart

insert image description here
The process of the recycling algorithm is consistent with that of the first fit, so it will not be repeated here.

3. Code implementation

nextFit algorithm, only the core allocation algorithm is given here, and the algorithm for inserting the job linked list and inserting the free linked list is consistent with the above.

    /*
     * NextFit算法 循环适应算法
     * */
    public int nextFit_distribution(ProcessNode p,int flag){
    
    
        UseNode useNode = new UseNode(p.getId(),p.getSize());
        int size = p.getSize();
        int count = 0;
        for(int i = flag; i < freeSpaceList.size();i++){
    
    //从上一次插入的空闲块的下一个空闲块开始循环寻找是否有合适大小的空闲块
            count++;
            if(size <= freeSpaceList.get(i).getSize()){
    
    
                //先处理空闲快链表
                FreeNode freeNode = freeSpaceList.get(i);
                useNode.setStartLocation(freeNode.getStartLocation());//插入进的占用块结点的起始位置为这个空闲块的起始位置

                if(size < freeNode.getSize()){
    
    //插入块的大小小于该空闲块的大小时,该空闲块的起始位置发生改变,大小发生改变
                    freeSpaceList.get(i).setStartLocation(freeNode.getStartLocation() + p.getSize());
                    freeSpaceList.get(i).setSize(freeNode.getSize() - p.getSize());
                }
                else{
    
    //如果插入块的大小和该空闲块的大小相同,从链表中删除这个空闲块
                    if(i == 0){
    
    
                        freeSpaceList.get(i+1).setBefore(-1);//如果这个空闲块是表头,那么将下一个空闲块的before置为-1;
                    }
                    else{
    
    
                        freeSpaceList.get(i-1).setNext(freeSpaceList.get(i).getNext());
                        freeSpaceList.get(i+1).setBefore(freeSpaceList.get(i).getBefore());
                    }
                }
                //在内存中显示分配情况
                for(int j = useNode.getStartLocation();j < useNode.getStartLocation() + useNode.getSize();j++){
    
    
                    if(j == useNode.getStartLocation()){
    
    
                        memory_space[j] = ""+useNode.getId()+" ";
                    }
                    else{
    
    
                        memory_space[j] = "+ ";
                    }
                }
                showMemory();
                //对分配列表进行操作
                addSpaceList(useNode);
                showUseSpaceList();
                showFreeSpaceList();
                if(i == freeSpaceList.size()-1){
    
    //如果该空闲块是最后一个空闲块,将flag置为0
                    flag = 0;
                }
                else {
    
    //否则将flag指向下一个空闲块
                    flag = i + 1;
                }
                return flag;
            }
            else {
    
    
                continue;
            }
        }
        if(count == freeSpaceList.size() - flag){
    
    
            System.out.println("没有合适的空闲块,插入失败");
        }
        return flag;
    }

4. The result display

The initial situation of memory and the situation of linked list:

insert image description here
insert image description here

Insert job block:

Please enter id: 2
Please enter occupied memory size: 15
insert image description here
insert image description here

The position of the inserted free block is the first free block, then the next time you insert it, start from the second

Insert the second job block:

insert image description here

insert image description here

Allocated to the next free block of the last allocated free block

Insert job chunks of size 30:

Please enter id: 6
Please enter occupied memory size: 30
insert image description here

Then insert, back to the first free block

insert image description here
Linked list situation at this time
insert image description here

Complete project download address

Memory allocation and deallocation complete project package

Guess you like

Origin blog.csdn.net/SherlockStark/article/details/110646524