双重释放或腐败三维数组用C [英] double free or corruption 3d array in C

查看:228
本文介绍了双重释放或腐败三维数组用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个双重释放或腐败的错误,同时释放一个3D阵列。谁能告诉我哪里是在code中的问题? 数组的大小是2 * N * N。这里的N值是100,即使没有铸件,相同的结果。
这里是code:

I get a 'double free or corruption' error while freeing up an 3d array. Can anyone please tell me where is the problem in the code? The size of the array is 2*N*N. Value of N here is 100. Even without casting, same result. Here is the code:

// Mallocing 
double ***h = malloc(2 * (sizeof(double**)));
for(i = 0; i < N; i++) {
    h[i] = malloc(N * sizeof(double*));
    for(j = 0; j < N; j++) {
        h[i][j] = malloc(N * sizeof(double));
    }
}

// Freeing
for(i = 0; i < N; i++) {
    for(j = 0; j < N; j++) {
        free(h[i][j]);
    }
    free(h[i]);
}
free(h);

该程序工作正常,但在最后我得到一个错误双自由或损坏(preV!):0x08cd24f8
中止(核心转储)。

The program works fine but at the end I get an error 'double free or corruption (!prev): 0x08cd24f8' Aborted (core dumped).

推荐答案

有关的第一个维度,可以分配2个元素:

For the first dimension, you allocate 2 elements:

double ***h = (double***) malloc(2 * (sizeof(double**)));

但你把它当作如果它有 N 元素:

for(i = 0; i < N; i++) {
    h[i] = ...

更改分配上的最外层循环比较和免费

for(i = 0; i < 2; i++) {

的malloc也不要投返回值。此外,您的code丢失的错误处理,如果分配失败,将打破。

Also don't cast return value of malloc. Also, your code is missing error handling, and will break if allocation fails.

这篇关于双重释放或腐败三维数组用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆