2013-04-10 2 views
2

사용자로부터 목록을 가져 오는 간단한 프로그램을 작성하려고합니다 (목록은 데이터가있는 구조체이며 다음 목록에 대한 포인터 임). 그런 다음 인쇄하십시오 . 코드가 제대로 작동하지만 인쇄 후 "처리 4.exe에서 0x011e1502의 처리되지 않은 예외 : 0xC0000005 : 0xCdcdcdcd 위치를 읽는 액세스 위반"오류가 발생합니다.C에서 처리되지 않은 예외로 처음으로 작업하는 경우

아무도 말해 줄 수 있습니까? 여기 내 코드 :

#include <stdio.h> 
#include <conio.h> 
#include <stdlib.h> 
typedef int list_data; 
typedef struct list 
{ 
    list_data number; 
    struct list* next_list; 
} list; //definition of a list 
list* create_list() 
{ 
    list* anchor; 
    anchor=(list*)malloc(sizeof(list)); 
    anchor->next_list=NULL; 
    return anchor; // allocates a memory for a list and returns address of first block 
} 
list* insert_list(list* current_position,list_data x) 
{ 
    list* temp; 
    temp=(list*)malloc(sizeof(list)); 
    temp->number=x; 
    temp->next_list=current_position->next_list; 
    current_position->next_list=temp; 
    return temp; //inserts a new block with a data of x 
} 
void printlist(list* anchor) 
{ 
    list* current_list=anchor->next_list; 
    while(current_list!=NULL) 
    { 
     printf("%3d -> ",current_list->number); 
     current_list=current_list->next_list; 
    } 
    printf("End\n"); 
} 
void scan_list(list* anchor) 
{ 
    int num1=1; 
    list* current_position=anchor; 
    printf("Enter values until 0\n"); 
    while(num1!=0) 
    { 
     scanf("%d",&num1); 
     if(num1) 
      current_position=insert_list(current_position,num1); 
    } 
} 
void main() 
{ 
    list* anchor; 
    anchor=create_list(); 
    scan_list(anchor); 
    printf("\n"); 
    printlist(anchor); 
    free(anchor); 
    getch(); 
} 
+1

나를 위해 잘 작동합니다. 너 어떻게 지내니? – nommyravian

+1

''anchor' = 메모리 누수 만 자유롭게합니다. 또한 명시 적으로 어느 행 **가 해당 액세스 위반 오류를 표시하는지 ** 알 수 있으면 좋을 것입니다. –

+0

printf ("% 3d ->", current_list-> number); 나에게 오류를 줬지만 지금은 효과가있는 것 같다. 간단한 재부팅으로 문제가 해결 된 것으로 보입니다. 시간을 낭비해서 죄송합니다. –

답변

2

값이 0xcdcdcdcd 인 단위화된 메모리 영역에 액세스하고 있습니다. 당신은 단순히 free, 첫 번째 요소를 삭제하여하지만 메모리 누수 또한 다른

void free_list(list* anchor){ 
    list* temp = anchor->next_list; 
    free(anchor); 
    while(temp->next_list){ 
     list* l = temp->next_list; 
     free(temp); 
     temp = l->next_list; 
    } 
} 

를 만드는 것이기 때문에, 목록을 반복하고 모든 노드를 확보, 모든 요소를 ​​삭제하여 목록은 다음 요소를 설정하지 않아야합니다 노드를 추가하고 당신이 당신의 기능에 이상 상호 참조가있는 경우 명시 적으로 NULL에,

list* insert_list(list* current_position,list_data x) 
{ 
    list* temp; 
    temp=(list*)malloc(sizeof(list)); 
    temp->number=x; 
    //temp->next_list=current_position->next_list; -> doesn't make sense 
    current_position->next_list=temp; 
    temp->next_list = NULL; //set to NULL 
    return temp; //inserts a new block with a data of x 
} 

난 당신이 명시 적으로 next 항목이라고 말하지 않았다 네 NULL 당신의 실제 끝을지나 반복 생각 명부.

+0

그래서, 무엇이 잘못입니까? –

1

게시 된 코드가 정상적으로 작동합니다. 사용자로부터 값을 가져 와서 올바르게 표시하고 있습니다. linux gcc를 사용하여 코드를 컴파일하고 경고를 피하기 위해 수정했습니다.

+0

내 컴퓨터에 어떤 이유로 든 없습니다 ... –

관련 문제