我在免费方面遇到麻烦。我想分配一个* chars二维数组并释放它们,但是在运行时失败。我正在学习指针,并且可能使它复杂化了。

  //NUMBEROFLINES, NUMBEROFDIE, and WIDTHOFDIE are some ints (3, 2, 3),
  int iLineSize, iLine, iDie;
  char **piDieString;

  piDieString = (char**)malloc(NUMBEROFLINES * sizeof(*piDieString)); //Allocate number of lines
  iLineSize = NUMBEROFDIE * WIDTHOFDIE * sizeof(char); //Size of line
  for(iLine = 0; iLine < NUMBEROFLINES; iLine++)
  {
     piDieString[iLine] = (char*)malloc(iLineSize); //Allocate size of lines
  }

  //Stuff happens

  /*Freeing*/
  for(iLine = 0; iLine < NUMBEROFLINES; iLine++)
     {
     free(piDieString[iLine]);
     }
  free(piDieString);

最佳答案

我相信//Stuff happens中有问题。

添加了打印以验证是否正在按以下方式正确分配和释放内存:

#include <stdio.h>
#define NUMBEROFLINES 3
#define NUMBEROFDIE 2
#define WIDTHOFDIE 3
int main(void) {

  int iLineSize, iLine, iDie;
  char **piDieString;

  piDieString = (char**)malloc(NUMBEROFLINES * sizeof(*piDieString)); //Allocate number of lines
  printf("Allocated piDieString: 0x%x\n",piDieString );
  iLineSize = NUMBEROFDIE * WIDTHOFDIE * sizeof(char); //Size of line

  for(iLine = 0; iLine < NUMBEROFLINES; iLine++)
  {
     piDieString[iLine] = (char*)malloc(iLineSize); //Allocate size of lines
     printf("Allocating piDieString[%d]: 0x%x\n",iLine,piDieString[iLine] );
  }

  //Stuff happens

  /*Freeing*/
  for(iLine = 0; iLine < NUMBEROFLINES; iLine++)
  {
     printf("Freeing piDieString[%d]: 0x%x\n",iLine,piDieString[iLine] );
     free(piDieString[iLine]);
  }

  printf("\nFreeing piDieString: 0x%x\n",piDieString );
  free(piDieString);
  return 0;
}


输出是这个,看起来还不错。

Allocated piDieString: 0x966e008
Allocating piDieString[0]: 0x966e018
Allocating piDieString[1]: 0x966e028
Allocating piDieString[2]: 0x966e038
Freeing piDieString[0]: 0x966e018
Freeing piDieString[1]: 0x966e028
Freeing piDieString[2]: 0x966e038

Freeing piDieString: 0x966e008


详细说明"but it fails at runtime" ...您看到崩溃了吗?如果是,请检查//Stuff happens进行无误的内存访问...

09-27 07:35