开发者

How to write a function to clean a memory pool in C

#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_typ开发者_如何学运维e;
    free(cur);
}
}

As code shown above, the function clearpool() in fact does not work !!! I am wondering if any expert can explain me why and help me solve it. thank you in advance.

Best Regards,


I think you wanted a struct, not a union for _data_block. The recursive union makes my head turn inside out. You have more problems, but this line:

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

suggests that you think &head->the_type is different from &head->next, which it isn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜