gpt4 book ai didi

c - 双重释放错误释放二维数组

转载 作者:行者123 更新时间:2023-11-30 19:16:53 26 4
gpt4 key购买 nike

我正在开发一个程序,该程序使用以二维数组作为字段的结构。但由于某种原因,每次我尝试使用 free_planet 函数时,都会收到双重释放错误。使用程序作为 valgrind 似乎问题出在第 49 行到第 51 行的指令上,但我真的不明白为什么。

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
typedef enum cell { SHARK, FISH, WATER } cell_t;

typedef struct planet {
unsigned int nrow;
unsigned int ncol;
cell_t ** w;
int ** btime;
int ** dtime;
} planet_t;


planet_t * new_planet (unsigned int nrow, unsigned int ncol) {
if ((int) nrow>=0 && (int) ncol>=0){
int i,j;
planet_t *a=malloc(sizeof(planet_t*));
a->nrow=nrow;
a->ncol=ncol;

a->w=(cell_t**) malloc(nrow * sizeof(cell_t*));
a->btime=(int**) malloc(nrow* sizeof(int*));
a->dtime=(int**) malloc(nrow* sizeof(int*));

for (i=0; i<nrow; i++){
a->w[i]=(cell_t*) malloc(ncol * sizeof(cell_t));
a->btime[i]=(int*) malloc(ncol*sizeof(int));
a->dtime[i]=(int*) malloc(ncol*sizeof(int));
}

for (i=0; i<nrow; i++)
for (j=0; j<ncol; j++)
a->w[i][j]=WATER;
return a;
}
errno=EINVAL;
return NULL;
}

void free_planet (planet_t* p){
int i;
int nrow=p->nrow;
for (i=0;i<nrow;i++){
if (p->w[i]!=NULL) free (p->w[i]);
if (p->btime[i]!=NULL) free (p->btime[i]);
if (p->dtime[i]!=NULL) free (p->dtime[i]);
}
if (p->w!=NULL) free (p->w);
if (p->btime!=NULL) free (p->btime);
if (p->dtime!=NULL) free (p->dtime);
if (p!=NULL) free (p);
return;
}

int main(){
planet_t *p; unsigned int x,y;

scanf( "%u %u", &x, &y);
p = new_planet(x,y);
free_planet (p);
return 0;
}

最佳答案

这是我看到的第一件事:

planet_t *a = malloc(sizeof(planet_t*)); 

当您应该为结构分配空间时,您却为指针分配了空间。所以应该是:

planet_t *a = malloc(sizeof(planet_t)); 

或者:

planet_t *a = malloc(sizeof(*a)); 

关于c - 双重释放错误释放二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29199652/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com