16,472
社区成员
发帖
与我相关
我的任务
分享
#include <map>
#include <string>
using namespace std;
const int MAX_BLOCKS = 256;
const int TOTAL_SIZE = 65536;
char buf[TOTAL_SIZE];
int ptr_alloced[MAX_BLOCKS];
int b_used[MAX_BLOCKS];
int cur_top = 0;
int currBlocks = 0;
char * my_malloc(int size)
{
int insert_pos = currBlocks;
//寻找可用的块
for (int i = 0; i<currBlocks && insert_pos==currBlocks; ++i)
{
if (b_used[i]==0)
{
if (i < currBlocks - 1)
{
if (ptr_alloced[i + 1] - ptr_alloced[i] >= size)
insert_pos = i;
}
}
}
if (insert_pos == currBlocks)
{
if (cur_top + size > TOTAL_SIZE)
return 0;
cur_top += size;
ptr_alloced[insert_pos] = cur_top;
}
b_used[insert_pos] = 1;
++insert_pos;
if (insert_pos > currBlocks)
currBlocks = insert_pos;
return &buf[ptr_alloced[insert_pos - 1]];
}
void my_free(const char * ptr)
{
int del = -1;
for (int i = 0; i<currBlocks; ++i)
{
if (ptr_alloced[i] + buf == ptr)
{
del = i;
break;
}
}
if (del >= 0)
b_used[del] = 0;
}
int main()
{
char * p1 = my_malloc(1024);
char * p2 = my_malloc(2048);
char * p3 = my_malloc(1024);
my_free(p2);
char * p4 = my_malloc(1024);
return 0;
}
const int MAX_BLOCKS = 256;
const int TOTAL_SIZE = 65536;
char buf[TOTAL_SIZE];
int ptr_alloced[MAX_BLOCKS];
int b_used[MAX_BLOCKS];
int cur_top = 0;
int currBlocks = 0;