释放2D动态分配的内存时出错

时间:2012-11-13 03:01:03

标签: c arrays malloc free dynamic-memory-allocation

我遇到一个问题,我尝试释放一些2D动态分配的内存,这些内存失败并崩溃cmd而没有任何有用的错误消息。

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

#define RANDOM_NUM 100

/*Function Prototypes*/
void fill_arrays(int**, int, int);
void find_minimum(int**, int, int);

int main(int argc, char* argv[]) {

    int arrays_size = 10;
    int num_of_arrays = 100;
    int j, i;
    int** arrays;
    int pid;

    srand(time(NULL));

    /*Dynamically allocate data*/
    arrays = (int**) malloc(num_of_arrays*sizeof(int*));
    for (i = 0; i < arrays_size; i++)  {
       arrays[i] = (int*) malloc(arrays_size*sizeof(int));
    }

    /*Function to fill arrays with random numbers*/
    fill_arrays(arrays, num_of_arrays, arrays_size);

    /*Function to find maximum element of each array*/
    find_minimum(arrays, num_of_arrays, arrays_size);

    for(i=0;i<num_of_arrays;i++)
    {
        //free(arrays[i]);
        printf("debug\n");
    }
    free(arrays);

    return (EXIT_SUCCESS);
}


void fill_arrays(int** array, int amount, int size) {
  int i, j; /*loop index variables*/

  for (i=0;i<amount;i++) {
     for(j=0;j<size;j++) {
        array[i][j] = rand()%RANDOM_NUM;
        printf("Array %d %d = %d\n", i , j ,array[i][j]);
     }
  }
}

void find_minimum (int** array, int amount, int size) {

   int minimum;
   int value;
   int c, i;
   int locationC = 0;
   int locationI = 0;

   for (c = 0; c < amount; c++)
   {
      minimum = array[c][0];
      for (i = 0; i < size; i++)
      {

         value = array[c][i];
         if (value < minimum)
         {
             minimum  = value;
             locationI = i;
         }
      }
   }
}

1 个答案:

答案 0 :(得分:3)

更改为

arrays = (int**) malloc(num_of_arrays*sizeof(int*));
for (i = 0; i < num_of_arrays; i++)  // num_of_arrays, not arrays_size
    arrays[i] = (int*) malloc(arrays_size*sizeof(*arrays[i]));

编辑,N * M阵列分配的一般形式。注意内存可能不连续。

T **a = malloc(sizeof *a * N);
if (a)
{
  for (i = 0; i < N; i++)
  {
    a[i] = malloc(sizeof *a[i] * M);
  }
}

如何免费

  for(i=0;i<num_of_arrays;i++)
    {
        free(arrays[i]);
        printf("debug\n");
    }

    free(arrays);