2014-06-18 5 views
0

모든 malloc에 ​​대해 우리는 종료 전에 해제해야합니다. valgrind 보고서를 기반으로, 나는 누출이 없습니다. 즉, valgrind는이 코드에 오류가 있다고보고합니다. Address 0x402613c is 4 bytes inside a block of size 8 free'dValgrind 오류가 있지만 누출이 없음

간략히하기 위해 아래는 노드 유형 및 노드를 malloc하거나 해제하는 코드 섹션을 보여주는 링크 된 목록 코드의 일부분입니다.

typedef struct node 
{ 
    int n; 
    struct node* next; 
} 
node; 

// global variable for the head of the list 
node* head = NULL; 

int main(void) 
{ 
    // user menu 
    while (true) 
    { 
     printf("Please choose an option (0, 1, 2): "); 
     int option = GetInt(); 

     switch (option) 
     { 
      // quit 
      case 0: 
       free_nodes(head); 
       printf("Goodbye!\n"); 
       return 0; 

// snipped: code that calls insert and print functions 

bool insert_node(int value) 
{ 
    // create new node 
    node* new_node = malloc(sizeof(node)); 
    if (new_node == NULL) 
    { 
     return false; 
    } 

    // snipped: some code that adds nodes to linked list 
} 

/** 
* Frees all of the nodes in a list upon exiting the program. 
*/ 
void free_nodes(node* list) 
{  
    // initialize pointer 
    node* curr_node = head; 

    // initialize variable for end of list 
    bool is_end = false; 

    // free nodes 
    while (!is_end) 
    { 
     // if an empty list, free node and exit 
     if (curr_node->next == NULL) 
     { 
      free(curr_node); 
      is_end = true; 
     } 
     // else free node list until end of list if found 
     else 
     { 
      free(curr_node); 
      curr_node = curr_node->next; 
     } 
    } 
} 
+1

'무료 (curr_node); curr_node = curr_node-> next;': 이미 릴리스 된 포인터는 사용하지 마십시오. – BLUEPIXY

답변

2

오류가 당신이 그것을 해제 후 해제 된 메모리에 대한 포인터를 사용하고 있음을 말하고있다 : 실제로 코드를보고

void *m = malloc(8); 
char *s = m + 4; 
free(m); 
*s = 29; // This would generate that warning. 
int c = *s; // This would also generate that warning. 

을 그리고, 그것은 예만큼이나 뻔뻔하다

free(curr_node); 
curr_node = curr_node->next; 

수정 : 위의 (자신의 comment 아웃 BLUEPIXY로 점)

node *next = curr_node->next; 
free(curr_node); 
curr_node = next; 
+0

많은 감사. @bluepixy와 메모를 본 후에는 다음 트랙을 추적하는 데 두 번째 포인터가 필요하다고 생각했지만 종료하기 전에 '자유 (다음)'해야 할 때 문제가 발생했습니다. – Andy

관련 문제