C语言内存管理

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>


#define MEM_SIZE 1024  // 内存总大小
#define BLOCK_SIZE 32  // 内存块大小

uint8_t mem[MEM_SIZE];  // 内存数组

typedef struct Block {
    uint8_t* start;  // 内存块起始地址
    uint8_t* end;    // 内存块结束地址
    bool free;       // 内存块是否空闲
} Block;

Block blocks[MEM_SIZE / BLOCK_SIZE];  // 内存块数组

// 初始化内存块
void init_blocks() {
    for (int i = 0; i < MEM_SIZE / BLOCK_SIZE; i++) {
        blocks[i].start = &mem[i * BLOCK_SIZE];
        blocks[i].end = &mem[(i + 1) * BLOCK_SIZE - 1];
        blocks[i].free = true;
    }
}

// 分配内存
uint8_t* my_malloc(size_t size) {
    int num_blocks = size / BLOCK_SIZE + (size % BLOCK_SIZE != 0);  // 需要的内存块数量
    int free_blocks = 0;  // 空闲内存块数量
    int start_block = -1;  // 起始内存块编号

    // 遍历内存块数组查找连续的空闲内存块
    for (int i = 0; i < MEM_SIZE / BLOCK_SIZE; i++) {
        if (blocks[i].free) {
            if (start_block == -1) {
                start_block = i;
            }
            free_blocks++;
            if (free_blocks == num_blocks) {
                break;
            }
        }
        else {
            free_blocks = 0;
            start_block = -1;
        }
    }

    // 如果找到连续的空闲内存块,则标记为已占用并返回内存块起始地址
    if (free_blocks == num_blocks) {
        for (int i = start_block; i < start_block + num_blocks; i++) {
            blocks[i].free = false;
        }
        printf("Allocated memory from 0x%p to 0x%p\n", blocks[start_block].start, blocks[start_block + num_blocks - 1].end);
        return blocks[start_block].start;
    }

    // 如果找不到连续的空闲内存块,则分配失败,返回空指针
    printf("Failed to allocate memory\n");
    return NULL;
}

// 释放内存
void my_free(void* ptr) {
    // 遍历内存块数组查找要释放的内存块
    for (int i = 0; i < MEM_SIZE / BLOCK_SIZE; i++) {
        if (ptr == blocks[i].start) {
            if (blocks[i].free) {
                printf("Memory at 0x%p has already been freed\n", ptr);
            }
            else {
                blocks[i].free = true;
                printf("Freed memory at 0x%p\n", ptr);
            }
            return;
        }
    }
    printf("Memory at 0x%p is not managed by this memory manager\n", ptr);
}

int main() {
    init_blocks();

    uint8_t* ptr1 = my_malloc(64);
    ptr1[0] = 10;
    printf("%d\n", ptr1[0]);
    ptr1[1] = 30;
    printf("%d\n", ptr1[1]);
    uint8_t* ptr2 = my_malloc(128);
    ptr2[1] = 50;
    printf("%d\n", ptr2[1]);
    uint8_t* ptr3 = my_malloc(32);
    ptr3[1] = 60;
    printf("%d\n", ptr3[1]);
    my_free(ptr2);
    my_free(ptr2);
    
    uint8_t* ptr4 = my_malloc(96);
    printf("%d\n", ptr2[1]);
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值