2011-04-14 3 views
2

나는 다음과 같은 구조체 및 방법을 사용하고 있습니다 : 나는 cellMinNeighbor()를 호출 할 때 내가 선택 기준에 따라 (cellGetNeighbors()에서) 8 개 양산 이웃 중 하나를 반환해야특정 malloc 된 배열 요소를 올바르게 해제하려면 어떻게합니까?

struct cell { 
    double x, y, h, g, rhs; 
    struct key *keys; 
}; 

void cellFree(struct cell *c) { 
    free(c->keys); 
    c->keys = NULL; 
    free(c); 
    c = NULL; 
} 

void cellCopyValues(struct cell *targetcell, struct cell *sourcecell) { 
    targetcell->x = sourcecell->x; 
    targetcell->y = sourcecell->y; 
    targetcell->h = sourcecell->h; 
    targetcell->g = sourcecell->g; 
    targetcell->rhs = sourcecell->rhs; 
    keyCopyValues(targetcell->keys, sourcecell->keys); 
} 

struct cell * cellGetNeighbors(struct cell *c, struct cell *sstart, struct cell *sgoal, double km) { 
    int i; 

    // CREATE 8 CELLS 
    struct cell *cn = malloc(8 * sizeof (struct cell)); 

    for(i = 0; i < 8; i++) { 
     cn[i].keys = malloc(sizeof(struct key)); 
     cellCopyValues(&cn[i], c); 
    } 


    return cn; 
} 

struct cell * cellMinNeighbor(struct cell *c, struct cell *sstart, struct cell *sgoal, double km) { 
    // GET NEIGHBORS of c 
    int i; 
    struct cell *cn = cellGetNeighbors(c, sstart, sgoal, km); 
    double sum[8]; 
    double minsum; 
    int mincell; 

    cellPrintData(&cn[2]); 

    // *** CHOOSE A CELL TO RETURN 
    mincell = 3; // (say) 


    // Free memory 
    for(i = 0; i < 8; i++) { 
     if(i != mincell) { 
      cellFree(&cn[i]); 
     } 
    } 

    return (&cn[mincell]); 
} 

을 - 그러나 현재의 방법을하는 I 무료로 적용한 다른 요소는 다음과 같은 오류를 표시합니다.

*** glibc detected *** ./algo: free(): invalid pointer: 0x0000000001cb81c0 *** 

내가 뭘 잘못하고 있니? 감사.

+0

()는''완전히 targetcell * = * sourcecell'을 수행하면 충분하다. – Philip

답변

5

배열을 할당 한 다음 특정 구성원을 확보하려고합니다. 귀하의 cn

8 struct cell의 배열에 할당되어 있지만 실제로 실제로 무료로 자신의 필요의 malloc를 사용하여 할당되지 않은 &cn[0], &cn[1], &cn[2]을 확보하기 위해 노력하고 있습니다. 당신 만 포인터는 malloc을 기억하는 하나의 좋은 규칙에 의해 얻었다을 해제해야

는 해방의 수는 mallocs의 수에 대응해야한다는 것입니다.

이 경우 cn과 개별 키가 있지만 &cn[1] 등이 아닙니다. 따라서이를 자유롭게하는 것은 실수입니다. 당신이 mallocs을 계산하면

, 당신은 9을 가지고 있지만 해방은 16이다. cellCopyValues ​​'에서

관련 문제