为什么这种动态分配会泄漏内存?

时间:2018-05-12 10:17:17

标签: c arrays malloc heap-memory

我在Windows上有一个动态扩展的bloom过滤器实现。每轮的扩展规模预计约为4MB,但每个扩展案例的分配为37.7MB。以下是代码:

声明:

unsigned char **bloom_filter;
const int EXPAND_SIZE=1;
const int COLUMNS=4397164;//~4MB
int bloom_filter_rows=1;

分配

bloom_filter=malloc(COLUMNS*sizeof(unsigned char*));
for(int i=0;i<bloom_filter_rows;i++)
    bloom_filter[i]=malloc(COLUMNS*sizeof(unsigned char));//initially bloom_filter is just COLUMNS size

扩展

int old_size=bloom_filter_rows;
int new_size=old_size+1;
char **temp_bf;
temp_bf=malloc(old_size*COLUMNS*sizeof(unsigned char*));
for(int i=0;i<old_size;i++)
    temp_bf[i]=malloc(bloom_filter_rows*COLUMNS*size0f(unsigned char));
//content is copied to temp_bf using iteration here

// free_old_bf()

for(int j=0;j<old_size;j++)
    free(bloom_filter[j];
free(bloom_filter);

//展开

bloom_filter=malloc(new_size*COLUMNS*sizeof(unsigned char*));
for(int i=0;i<new_size;i++)
    bloom_filter[i]=malloc(COLUMNS*sizeof(unsigned char));
//copy back old content here

//免费temp_bf

for(int j=0;j<old_size;j++)
    free(temp_bf[j];
free(temp_bf);

0 个答案:

没有答案