内存分配

 

 

 思路:定义全局变量数组保存,通过map映射。

#include <iostream>
#include <string>
#include <map>
using namespace std;

class MiniMemoryPool {
private:
    int total[100] = {0};
    int totalmem = 100;
    map<int, int> mem;
public:

    bool isempty(int s, int size) {
        for (int i = 0; i < size; i++) {
            if (total[s + i]) {
                return false;
            }
        }
        return true;
    }
    // 返回分配的内存首地址,失败返回 -1
    int Request(int size)
    {
        if (size == 0 || size > totalmem) {
            return -1;
        } else {
            for (int i = 0; i < 100; i++) {
                if (isempty(i, size)) {
                        totalmem -= size;
                        mem[i] = size;
                        for(int k = 0; k < size;k++) {
                            total[k+i] = 1;
                        }
                        return i;
                    }
            }
        }
        return -1;
    }

    // 释放内存地址, 成功返回 true, 失败返回 false
    bool Release(int startAddr)
    {
        if (mem[startAddr]) {
            totalmem += mem[startAddr];
            for (int i = 0; i < mem[startAddr]; i++) {
                total[i + startAddr] = 0;
            }
            mem.erase(startAddr);
            return true;
        }
        return false;
    }
};

int main()
{
    int num;
    cin >> num;

    MiniMemoryPool pool;
    for (int loop = 0; loop < num; loop++) {
        string line;
        cin >> line;

        string commond = line.substr(0, line.find_first_of('='));
        if (commond == "REQUEST") {
            int size = stoi(line.substr(line.find_first_of('=')+1));
            int result = pool.Request(size);
            if (result != -1) {
                cout << result << endl;
            } else {
                cout << "error" << endl;
            }
        } else if (commond == "RELEASE") {
            int addr = stoi(line.substr(line.find_first_of('=')+1));
            if (!pool.Release(addr)) {
                cout << "error" << endl;
            }
        }
    }

    return 0;
}

 

posted @ 2022-02-15 21:57  A-inspire  Views(48)  Comments(0Edit  收藏  举报