c - 我的动态内存分配/多维​​数组空闲 C 代码有什么问题

标签 c arrays malloc free multidimensional-array

我正在调试 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/

相关文章:

c - 为什么我们要为一个int数据的链表分配内存?

c++ - 从套接字卡住中读取

c - 声明函数printf

javascript - ES5 风格的连接数组。将数组合并为一个

javascript - 如何在不硬编码的情况下解决数组问题?

c - 将指针A分配给B。释放A后,B仍然存在

c - 为什么以下代码会产生段错误?

c - C 中的内存泄漏 - 动态数组丢失数据

C将指针传递给函数混淆

ios - 在 Swift/iOS 中从 UITableView 删除行并从 NSUserDefaults 更新数组的正确方法