c- 分配和释放二维数组

c- Allocate and Free 2D Array

我正在尝试编写 2 个函数,一个用于动态分配二维数组,另一个用于释放此二维数组:

int allocate(int **array, unsigned int rows, unsigned int columns){
  int i;
  for (i = 0; i < rows; i++) {
    array[i] = malloc(columns * sizeof (int));
  }
  /* Code fo fill the array*/
  return 1;
}
void de_allocate(int **v, unsigned int rows) {
  int i;
  for (i = 0; i < rows; i++) {
    free(v[i]);
  }
  free(v);
}
int main(int argc, char **argv) {
    int rows, columns;
    rows = atoi(argv[1]);
    columns = atoi(argv[2]);
    int *ipp[rows];
    allocate(ipp, rows, columns);
    de_allocate(ipp,rows);  
    return 0;
}

我必须尊重分配函数签名:

int allocate(int **array, unsigned int rows, unsigned int columns)

并且在分配函数结束时,ipp 必须能够访问分配的二维数组。

分配函数是正确的,但在de_allocate函数中我有一个SIGABRT信号

问题是您正在尝试使用代码 free(v);

释放堆栈分配的变量

如果分配了指针数组,您可以这样做,但是您在 main 函数中使用 int *ipp[rows];

在本地声明它

如果您想保持 de_allocate 不变,请将其更改为 int **ipp = malloc(sizeof(int*)*rows);

您可以使用

进行测试
#include <stdio.h>
#include <stdlib.h>

int allocate(int **array, unsigned int rows, unsigned int columns){
  int i;
  for (i = 0; i < rows; i++)
  {
    array[i] = malloc(columns * sizeof (int));
  }

  /* Code fo fill the array*/
  return 1;
}

void de_allocate(int **v, unsigned int rows) {
  int i;
  for (i = 0; i < rows; i++)
  {
    free(v[i]);
  }
  free(v);
}

int main(int argc, char **argv) 
{
    int rows, columns;
    int temp = 0;
    rows = atoi(argv[1]);
    columns = atoi(argv[2]);

    int **ipp = malloc(sizeof(int*)*rows);

    allocate(ipp, rows, columns);

    for (int i=0; i<rows; i++)
        for (int j=0; j<columns; j++)
            ipp[i][j] = temp++;

    for (int i=0; i<rows; i++)
        for (int j=0; j<columns; j++)
            printf("ipp[%d][%d] = %d\n", i, j, ipp[i][j]);

    de_allocate(ipp,rows);
    return 0;
}
void de_allocate(int **v, unsigned int rows) {
  int i;
  for (i = 0; i < rows; i++) {
    free(v[i]);
  }
  free(v);
-----^----
here you are attempting to free a variable for which you didn't dynamically allocate memory in the first place

}