2010-08-10 52 views
0
#include<stdio.h> 
#include<stdlib.h> 
typedef struct _anyT { 
int val; 
} anyT; 

#define UNITS 10 

typedef union _data_block { 
       union _data_block *next; 
       anyT the_type; 

} data_block; 

static data_block *free_list = NULL; 

static void moremem(void) { 
    int i; 
    data_block *more = calloc(sizeof(data_block),UNITS); 
    for(i = 0; i < UNITS; i++) { 
     more[i].next = free_list; 
     free_list = more + i; 
    } 
} 

anyT *allocanyT(void) { 
    data_block *current; 
    if(free_list == NULL) { 
     moremem(); 
     return allocanyT(); 
    } 
    current = free_list; 
    free_list = free_list->next; 
    return &(current->the_type); 

} 

void freeanyT(anyT *x) 
{ 
    ((data_block *)x)->next = free_list; 
    free_list = (data_block *)x; 
} 

void clearpool() { 
data_block *head; 
anyT* cur; 
for(head=free_list;head;head=free_list) { 
    free_list=free_list->next; 
    cur=(anyT*)&head->the_type; 
    free(cur); 
} 
} 

如上面代码所示,函数clearpool()实际上并不工作!我想知道 如果任何专家可以解释我为什么,并帮助我解决它。先谢谢你。如何编写一个清除内存池的函数C

最好的问候,

+0

你怎么知道它不起作用?怎么了? – nmichaels 2010-08-10 20:17:01

+0

我不知道你的意思是“不行”;我看到一些可能成为问题的东西,但我不知道它们是否是问题。请描述这是干什么的,以及你期望它做什么。 – zwol 2010-08-10 20:19:27

+0

clearpool函数应该清理池中的那些分配的对象。“不起作用”意味着它实际上不会像我期望的那样使用valgrind来检查它的工作 。谢谢 – HKK 2010-08-10 20:46:02

回答

2

我想你想要一个结构,而不是_data_block的联合。递归联合让我的头转向内部。您有更多的问题,但此行:

cur=(anyT*)&head->the_type;

建议您认为&head->the_type&head->next不同,它不是。

+0

对递归工会造成的外部大脑的+1! – bstpierre 2010-08-11 02:35:51

+0

那你怎么能这样做? – HKK 2010-08-13 13:23:02