#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;
}
C语言内存管理
最新推荐文章于 2024-10-11 21:03:22 发布