【问题标题】:free() gives me an error invalid conversation from chat to voidfree() 给了我一个错误,从聊天到无效的对话无效
【发布时间】:2019-02-27 15:39:11
【问题描述】:

我正在学习有关动态内存的知识并尝试编写一些代码。但是,当我尝试运行它时,它会输出错误并且我无法解决该错误。 malloc() 的用法一定有问题,但我不确定。

这里的错误点-> free(cube[c][b][a]);

谢谢!

这是我的代码:

#include <stdio.h>
#include <stdlib.h>

#define DIM 4

void showCube(char**** cube, int dim) {
  int a, b, c;
  for(c = 0; c < dim; c++) {
    for(b = 0; b < dim; b++) {
      for(a = 0; a < dim; a++) {
        printf("%c ", *cube[c][b][a]); 
      }
      printf("\n");
    }
    printf("50*-\n");
  }
}

int main() {
  char*** cube = (char***)malloc(sizeof(char**) * DIM);
  int a, b, c;
  for(c = 0; c < DIM; c++) {
    cube[c] = (char**)malloc(sizeof(char**) * DIM);
    for(b = 0; b < DIM; b++) {
      cube[c][b] = (char*)malloc(sizeof(char*) * DIM);
      for(a = 0; a < DIM; a++) {
        cube[c][b][a] = ((a + b + c) % 26) + 'A'; 
      }
    }
  }

  showCube(&cube, DIM);

  for(c = 0; c < DIM; c++) {
    for(b = 0; b < DIM; b++) {
      for(a = 0; a < DIM; a++) {
        free(cube[c][b][a]); 
      }
      free(cube[c][b]);
    }
    free(cube[c]);
  }
  free(cube);
  return 0;
}

【问题讨论】:

  • 这不是不言自明吗? cube[c][b][a]char 而不是指针。
  • @EugeneSh。我需要在代码中修复什么才能使其正常工作?
  • 既然DIM 是一个编译时常量,为什么还要搞乱动态分配呢?只需将main 中的多维数据集声明为char cube[DIM][DIM][DIM]; 并完全避免malloc()free()。您也可以对接受该类型的函数参数使用相同的类型,这将修复showCube() 中的错误之一。

标签: c memory-management malloc free


【解决方案1】:

当你为数组分配空间时,你在三个层次上分配内存:

  char*** cube = (char***)malloc(sizeof(char**) * DIM);
  int a, b, c;
  for(c = 0; c < DIM; c++) {
    cube[c] = (char**)malloc(sizeof(char**) * DIM);
    for(b = 0; b < DIM; b++) {
      cube[c][b] = (char*)malloc(sizeof(char*) * DIM);
      for(a = 0; a < DIM; a++) {
        cube[c][b][a] = ((a + b + c) % 26) + 'A'; 
      }
    }
  }

但尝试在 4 个级别释放它:

  for(c = 0; c < DIM; c++) {
    for(b = 0; b < DIM; b++) {
      for(a = 0; a < DIM; a++) {
        free(cube[c][b][a]); 
      }
      free(cube[c][b]);
    }
    free(cube[c]);
  }
  free(cube);

cube[c][b][a]char,而不是char *,所以你不能释放它。摆脱最里面的循环。

  for(c = 0; c < DIM; c++) {
    for(b = 0; b < DIM; b++) {
      free(cube[c][b]);
    }
    free(cube[c]);
  }
  free(cube);

【讨论】:

    猜你喜欢
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    相关资源
    最近更新 更多