我有一个问题,我尝试释放一些 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("debugn");
}
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 = %dn", 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;
}
}
}
}
更改为
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("debugn");
}
free(arrays);