我正在调试 C 程序。需要一个巨大的 3 维数据数组。我开发了两个用于内存分配/释放的函数。
mm()
是为分配而设计的,引用一个记录每个维度大小的数组(你可以在main()
中看到)。 ff()
用于释放内存。
我在 fr()
执行后用 top 命令测试了我的代码。它显示内存未释放。
任何人都可以阐明它吗?
提前致谢!
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
28338 fsdiag 25 0 165m 164m 1208 R 63.2 26.0 0:00.33 a.out
3439 root 15 0 31740 1180 21m S 1.9 0.2 10:56.47 X
int main(){
unsigned char ***arr;
int dim_len[4]={8832,256,64,0}; // for 3-D array, 0 is mark of tail
unsigned char *p;
mm( &p, dim_len, 0); arr = (unsigned char ***)p;
ff( (unsigned char **)&arr, dim_len);
while(1){}
return 0;
}
void mm( unsigned char **a,
int dim_len[], //dimension size array guarded by 0 in the tail
unsigned char data){ //preset data
if( *dim_len ){
int i;
switch(*(dim_len+1)){
case 0://when allocate memory for unsigned char
*a = malloc( sizeof(unsigned char) * (*dim_len));
break;
default://when allocate memory for pointers
*a = malloc( sizeof(unsigned char *) * (*dim_len));
for( i=0; i<(*dim_len); i++){
mm( (unsigned char **)&((*a)[i*4]), dim_len+1, data);
}
break;
}//end of switch
}//end of if
return;
}
void ff( unsigned char **a,
int dim_len[]){//dimension size array guarded by 0 in the tail
if( *dim_len ){
int i;
switch(*(dim_len+1)){
case 0://when free memory for unsigned char
free( *a);
break;
default://when free memory for pointers
for( i=0; i<(*dim_len); i++){
ff( (unsigned char **)&((*a)[i*4]), dim_len+1); //pointer needs 4 bytes storage
}
free( *a );
break;
}//end of switch
}//end of if
*a = NULL;
return;
}
最佳答案
您应该只分配一 block 内存,其大小为 dim_len
中数字的乘积。
您分配的数据是零散的并且比它应该的更大,我很难想象您的代码有任何好处的任何场景。
关于c - 我的动态内存分配/多维数组空闲 C 代码有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6580868/