2013-03-19 2 views
0

GDB에서이 프로그램을 디버깅하려고 시도했지만 매우 이상한 충돌 오류 (SIGABRT)가 발생합니다. 그것은 내 팝 기능에서 발생하지만 나는 그 이유를 모른다. 누군가 나를 도울 수 있습니까? 고마워!GDB에서 이상한 충돌 오류

나는 GDB를 밟았으며 i = 9 일 때 팝 함수에서 자유 (tmp) 할 때 충돌이 일어날 것으로 생각한다.

#include <stdio.h> 
#include <stdlib.h> 

#define SIZE 10 
#define FALSE 0 
#define TRUE 1 


struct linkedStruct 
{ 
    int elem; 
    struct linkedStruct* next; 
}; 

typedef struct linkedStruct linked; 
typedef linked* linkedPtr; 

void push (linkedPtr* hd, int val) 
{ 
    linkedPtr ptr = (linkedPtr) malloc (sizeof(linked)); 
    ptr->elem = val; 
    ptr->next = *hd; 
    *hd = ptr; 
} 

int isEmpty (linkedPtr hd) 
{ 
    if (hd == NULL) 
     return TRUE; 
    else 
     return FALSE; 
} 


int top (linkedPtr hd) 
{ 
    return (hd->elem); 
} 

void pop (linkedPtr hd) 
{ 
    linkedPtr tmp = hd; 
    hd = hd->next; 
    free (tmp); 
} 

void show (linkedPtr hd) 
{ 
    while (hd != NULL) 
    { 
     printf ("%d, ", hd->elem); 
     hd = hd->next; 
    } 
    printf ("\n"); 
} 

int main (int argc, char**argv) 
{ 
    linkedPtr head = NULL; 
    int i; 
    int temp; 

    /* push 10 random values onto the stack showing the stack growing */ 
    for (i = 0 ; i < SIZE; ++i) 
    { 
     temp = rand() % 100; 
     printf ("In main(): temp: %6d\n", temp); 
     push (&head, temp); 
     show (head); 
    } 

    printf ("\n"); 

    /* remove the value from the stack */ 
    while (!isEmpty(head)) 
    { 
     printf ("Top of stack value is: %d\n", top(head)); 
     pop (head); 
    } 
} 
+0

힌트 : 무슨 일이 때 하나 개의 요소가있어? –

+1

'hd = hd-> next'와 같은'hd'의 변경 사항은'pop()'이 끝난 후에도 유지되지 않을 것입니다. 맞습니까? – m0skit0

답변

0

여기서 실제 문제 hd 변경이 이미 해제 된 메모리에 호출되는 free() 리드 호출자에게 보이지 않는 것으로하고, 따라서 그것은 정의되지 않은 동작을 생성한다.

귀하의 pop()는 다음과 같이한다 :이 같은

void pop (linkedPtr* hd) 
{ 
    linkedPtr tmp = *hd; 
    *hd = (*hd)->next; 
    free (tmp); 
} 

및 전화를 :

pop(&head); 
+2

'pop()'은 값으로 전달되므로'hd'를 변경하지 않습니다. – m0skit0

+0

@ m0skit0 : 그래, 나도 알아 챘다. 조금 늦었다. 전달 된 포인터에'next'를 할당하는 것은 호출자에게'NULL '을 전달하는 방법이기 때문에 여기에 필요합니다. – LihO

+0

고마워! – juice