当我试图释放C.中分配的内存时,我遇到了一个问题
int i,j,**redmatrix, **bluematrix, **greenmatrix;
double **weigthMatrix,fsom;
weigthMatrix = (double**) calloc(radius*2+1,sizeof(double*));
redmatrix = (int**) calloc(radius*2+1,sizeof(int*));
bluematrix = (int**) calloc(radius*2+1,sizeof(int*));
greenmatrix = (int**) calloc(radius*2+1,sizeof(int*));
if(weigthMatrix==NULL || redmatrix==NULL || bluematrix==NULL || greenmatrix==NULL){
printf("%sn", "Error: probleem met geheugenallocatie");
exit(1);
}
for(i=0;i<radius*2+2;i++){
weigthMatrix[i] = (double*) calloc(radius*2+1,sizeof(double));
redmatrix[i] = (int*) calloc(radius*2+1,sizeof(int));
bluematrix[i] = (int*) calloc(radius*2+1,sizeof(int));
greenmatrix[i] = (int*) calloc(radius*2+1,sizeof(int));
if(weigthMatrix[i]==NULL || redmatrix[i]==NULL || bluematrix[i]==NULL || greenmatrix[i]==NULL){
printf("%sn", "Error: probleem met geheugenallocatie");
exit(1);
}
}
for(i=0;i<radius*2+1;i++){
free(weigthMatrix[i]);
free(redmatrix[i]);
free(bluematrix[i]);
free(greenmatrix[i]);
}
free(redmatrix); //MY PROGRAM CRASHES HERE
free(bluematrix);
free(greenmatrix);
free(weigthMatrix);
free_image(©Image);
当我试图释放数组的顶级时,我的程序崩溃。我不知道我做错了什么。我想我把所有东西都分配对了吗?
您为radius*2+1
元素保留空间
redmatrix = (int**) calloc(radius*2+1,sizeof(int*));
但是你用radius*2+2
元素填充并释放数组
for(i=0;i<radius*2+2;i++){
redmatrix[i] = (int*) calloc(radius*2+1,sizeof(int));
for(i=0;i<radius*2+2;i++){
free(redmatrix[i]);
...
更改为
for(i=0;i<radius*2+1;i++){
redmatrix[i] = (int*) calloc(radius*2+1,sizeof(int));
...
for(i=0;i<radius*2+1;i++){
free(redmatrix[i]);
...
请不要投射malloc