2016-09-27 3 views
0

C에서 단일 연결 목록을 구현하기위한 코드를 작성했습니다. 코드가 컴파일되는 동안 코드를 실행하려고 할 때 세그멘테이션 오류가 발생합니다.C - 세그먼트 화 오류 오류의 단일 연결 목록 프로그램

코드입니다 :

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

struct Node{ 
    int data; 
    struct Node* next; 
}; 
struct Node* head; 

void InsertAtPosition(int data, int n){ 
    int i; 
    struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node*)); 
    temp1->data = data; 
    temp1->next = NULL; 
    if(n == 1){ 
      temp1->next = head; 
      head = temp1; 
      return; 
    } 
    struct Node* temp2 = head; 
    for(i=0; i<n-2; i++){ 
      temp2 = temp2->next; 
    } 
    temp1->next = temp2->next; 
    temp2->next = temp1; 
} 

void Print(){ 
    struct Node* temp = head; 
    printf("List is: \n"); 
    while(temp != NULL){ 
      printf("\t%d\n", temp->data); 
      temp = temp->next; 
    } 
} 

int main(){ 
    head = NULL; 
    InsertAtPosition(10, 1); 
    InsertAtPosition(11, 2); 
    InsertAtPosition(12, 3); 
    Print(); 
    return 0; 
} 

코드는 오류 Segmentation fault (core dumped)을주고있다.

정확히 무엇을하고 있습니까?

+1

말해봐? –

+4

목록이 비어있을 때 위치 10에 어떻게 삽입 할 수 있습니까? – user3386109

+6

'struct Node * temp1 = (struct Node *) malloc (sizeof (struct Node *)); 틀린. – EOF

답변

3
(struct Node*)malloc(sizeof(struct Node*)) 

잘못된 포인터 크기의 메모리를 만듭니다. 시도해보십시오.

(struct Node*)malloc(sizeof(struct Node)) 
+0

그리고 for (i = 0; i next; }'목록의 크기를 확인해야합니다.리스트보다 큰 "n"을 넘기면 또 다른 세그먼테이션 오류가 발생합니다 – Alexi

+1

좋은 연습으로'sizeof (type() 대신에'type * var = malloc (sizeof (* var))')', 이것은 미래의 변경을 덜 오류가 발생하기 쉽고 (더 간결합니다;)) –

0

앞의 답변에서 다뤘습니다. 그러나 프로그램에서 하나의 세그 폴트를 볼 수 있습니다. n 값이 목록의 크기를 초과하면이 코드 부분이 중단됩니다.

당신은 함수 호출의 순서를 변경하면 기본 기능에
for(i=0; i<n-2; i++){ 
     temp2 = temp2->next; 
} 

, 당신은이 다음과 같이 변경을하게 해결하려면이 segfault의

InsertAtPosition(11, 2); 
InsertAtPosition(10, 1); 
InsertAtPosition(12, 3); 

을 볼 수 디버거를 무엇

for(i=0; i<n-2; i++){ 
     if (temp2 == NULL){ 
      return; 

      /*or break instead of return as per your requirement. 
      Adding break will add the element to the end of 
      the list whenever `n` exceeds size of list*/ 
     } 
     temp2 = temp2->next; 

}