69,373
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
struct mblock
{
struct mblock *next; // 指向堆中下一个内存块的指针.
char *start; //内存块起始.
char *end; //内存块结束.
char *avail; //可用内存块.
};
typedef struct heap
{
struct mblock head; // 内存块的头.
struct mblock *last; // 内存块的尾.
}*Heap;
static struct mblock *free_blocks;
struct heap string_heap;
#define MBLOCK_SIZE (4 * 1024)
// 字节对齐.
#define ALIGN_SIZE 8
#define ALIGN(size, align) ((size + align - 1) & (~(align - 1)))
void init_heap(Heap hp);
void init_heap(Heap hp)
{
hp->head.next = NULL;
hp->head.start = hp->head.end = hp->head.avail;
hp->last = &hp->head;
}
void *heap_allocate(Heap hp, int size)
{
struct mblock *blk = NULL;
// 字节对齐.
size = ALIGN(size, ALIGN_SIZE);
blk = hp->last;
// 申请的大小 > 尾巴 - 可用的空间.
puts("-------------------");
while (size > blk->end - blk->avail)
{
puts("fjdffk");
if ((blk->next = free_blocks) != NULL)
{
printf("exit...");
}
else
{
puts("-------------------333");
int m = size + MBLOCK_SIZE + sizeof(struct mblock);
blk->next = (struct mblock*)malloc(m);
blk = blk->next;
if (blk == NULL)
{
}
blk->end = (char*)blk + m;
}
blk->avail = blk->start = (char*)(blk + 1);
blk->next = NULL;
hp->last = blk;
puts("-------------------4444");
}
puts("-------------------222");
blk->avail += size;
return blk->avail - size;
}
void free_heap(Heap hp)
{
hp->last->next = free_blocks;
free_blocks = hp->head.next;
init_heap(hp);
}
int main(int argc, char *argv[])
{
init_heap(&string_heap);
struct x
{
int x1;
int y1;
int a;
int b;
};
struct x *p = heap_allocate(&string_heap, 100);
p->x1 = 3;
p->y1 = 4;
printf("%d\n", p->x1);
free_heap(&string_heap);
return 0;
}