-1

私は、フィールドとして 2 次元配列を持つ構造体を使用するプログラムに取り組んでいます。しかし、何らかの理由で毎回 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;
}
4

1 に答える 1

1

最初に目にするのは次のとおりです。

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

構造体にスペースを割り当てる必要があるときに、ポインターにスペースを割り当てています。したがって、次のようになります。

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

または:

planet_t *a = malloc(sizeof(*a)); 
于 2015-03-22T20:56:03.453 に答える