这段代码会内存泄露吗?

hailongqiu 2013-05-03 02:52:56

#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;
}
...全文
177 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
cmail2005 2013-05-05
  • 打赏
  • 举报
回复
blk->next = (struct mblock*)malloc(m);这里分配内存。 free_blocks = hp->head.next;把分配的内存首地址赋给了free_blocks, 在free_heap(&string_heap);之后加 mblocks * p = free_blocks; while(free_blocks!=0) { p = p->next; free(free_blocks); free_blocks = p; } 试试。
hugett 2013-05-04
  • 打赏
  • 举报
回复
这个。。可以用检测工具自己查。。
houzhenghui123 2013-05-04
  • 打赏
  • 举报
回复
只要能立马结束的程序都不会泄露的!
恨天低 2013-05-03
  • 打赏
  • 举报
回复
用工具检查吧。
jiandingzhe 2013-05-03
  • 打赏
  • 举报
回复
自己用valgrind跑一下不就知道了
starytx 2013-05-03
  • 打赏
  • 举报
回复
有,泄露了4216字节 [6824] normal block at 0x005DB078, 4216 bytes long.

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧