2016-06-13 2 views
2

나는 매우 기본적인 단독 링크 목록 구현을 가지고 있습니다. 그러나 구현시 문제는 목록의 시작 부분에 여분의 0을 인쇄하는 반면 명시 적으로이 추가 노드에 대한 저장소를 할당하지 않는다는 것입니다. 같은 코드는 다음과 같습니다 -링크 된 목록은 처음에 여분의 0을 인쇄합니다.

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

#define LEN 7 

/* List node data structure */ 
typedef struct _ll_node_ { 
    int data; 
    struct _ll_node_ *next; 
} node; 

/* 
* @brief Utility to print the state of the list 
*/ 
void print_list(node *head) 
{ 
    int i = 0; 
    node *tmp = head; 
    while (tmp) 
    { 
     printf("Node:\t%d,\tValue:\t%d\n", ++i, tmp->data); 
     tmp = tmp->next; 
    } 
    printf("\n"); 
} 

/* 
* @brief Utility to add nodes to the list 
*/ 
node *add_node(node *head, int data) 
{ 
    node *tmp; 
    if (head == NULL) 
    { 
     head = malloc(sizeof(node)); 
     assert(head != NULL); 
     head->data = data; 
     head->next = NULL; 
    } 
    else 
    { 
     tmp = head; 
     while (tmp->next) 
      tmp = tmp->next; 
     tmp->next = malloc(sizeof(node)); 
     assert(tmp->next != NULL); 
     tmp = tmp->next; 
     tmp->data = data; 
     tmp->next = NULL; 
    } 
    return head; 
} 

/* 
* @brief Driver function 
*/ 
int main(int argc, char *argv[]) 
{ 
    node *head = NULL; 
    int i = 0; 
    /* Allocate memory */ 
    head = malloc(LEN * sizeof(node)); 
    assert(head != NULL); 
    /* Populate the list */ 
    for (; i < LEN; i++) 
     head = add_node(head, rand() % 1000); 
    /* Print its state */ 
    print_list(head); 

    return 0; 
} 

누군가 내가 잘못하고있는 부분을 알아낼 수 있습니까?

System information: 
    Distributor ID: Ubuntu 
    Description: Ubuntu 14.04.3 LTS 
    Release:  14.04 
    Codename:  trusty 
+1

이 두 줄의 주석은 다음과 같습니다. head = malloc (LEN * sizeof (node)); assert (head! = NULL);'나머지는 모두 정상입니다. –

답변

4

이 문을

head = malloc(LEN * sizeof(node)); 

은 적합하지 않습니다. 그것을 제거하십시오.

초기화되지 않은 배열을 할당했습니다. 따라서 add_node 함수를 사용하면 정의되지 않은 동작이 발생합니다.

머리글을 참조로 전달하면 함수 add_node을 간단하게 작성할 수 있습니다. 예 :

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

#define LEN 7 

/* List node data structure */ 
typedef struct _ll_node_ { 
    int data; 
    struct _ll_node_ *next; 
} node; 

/* 
* @brief Utility to print the state of the list 
*/ 
void print_list(node *head) 
{ 
    int i = 0; 
    node *tmp = head; 
    while (tmp) 
    { 
     printf("Node:\t%d,\tValue:\t%d\n", ++i, tmp->data); 
     tmp = tmp->next; 
    } 
    printf("\n"); 
} 

/* 
* @brief Utility to add nodes to the list 
*/ 
int add_node(node **head, int data) 
{ 
    int success; 

    while (*head != NULL) head = &(*head)->next; 

    *head = malloc(sizeof(node)); 

    success = *head != NULL; 

    if (success) 
    { 
     (*head)->data = data; 
     (*head)->next = NULL; 
    } 

    return success; 
} 

/* 
* @brief Driver function 
*/ 
int main(void) 
{ 
    node *head = NULL; 
    int i = 0; 

    srand((unsigned int)time(NULL)); 

    /* Populate the list */ 
    for (; i < LEN; i++) 
     add_node(&head, rand() % 1000); 
    /* Print its state */ 
    print_list(head); 

    return 0; 
} 
6

이미 주에서 머리 따라서 첫 번째 노드가 데이터를 할당되지 않습니다 따라서 기본적으로는 0 이 시도 될 걸립니다 메모리를 할당됩니다

int main(int argc, char *argv[]) 
{ 
    node *head = NULL; 
    int i = 0; 

    /* Populate the list */ 
    for (; i < LEN; i++) 
     head = add_node(head, rand() % 1000); 
    /* Print its state */ 
    print_list(head); 

    return 0; 
} 
+0

@ vlad-from-moscow와 priyansh-goel을 지적 해 주셔서 감사합니다. 완전히 놓쳤습니다. – rurtle

+0

@rurtle : 감사하는 더 좋은 방법은 대답을 수락하는 것입니다. –

+0

@rurtle : 나는 그 점에 절망하지 않습니다. 당신을 위해 어떤 대답이라도 받아 들여야합니다. 블라드의 대답을 받아들이면 괜찮습니다. :) 그 문제가 해결되면 항상 대답을 받아 들여야합니다 :) –

관련 문제