Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am creating two new lists with C, the code is shown below

 struct ListNode {
  int val;
  struct ListNode *next;
};

struct ListNode* createList(int list[], int listsize){
    struct ListNode *newlistnode;
    struct ListNode *curlistnode;
    struct ListNode *listhead;
    for(int i = 0; i < listsize; i++){
        newlistnode = (struct ListNode*) malloc(sizeof(struct ListNode));
        newlistnode -> val = list[i];
        newlistnode -> next = NULL;
        if(listhead == NULL)
            listhead = newlistnode;
        else
            curlistnode ->next = newlistnode;
        curlistnode = newlistnode;
    }
    return listhead;
}

int main(){
    int a[4] = {2, 4, 3};
    int b[4] = {5, 6, 4};
    int listsize = 3;
    struct ListNode* list_a = createList(a, listsize);
    struct ListNode* list_b = createList(b, listsize);
    return 0;
}

here is what I got:
list_a : 2->4->3->NULL
list_b: 2->4->3->5->6->4->NULL
I am confused, can anyone help me?

question from:https://stackoverflow.com/questions/65947319/c-create-two-new-lists-but-get-wrong-result

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
99 views
Welcome To Ask or Share your Answers For Others

1 Answer

The problem is you didn't initialize the pointers in your function body. This is undefined behavior as mentioned.

struct ListNode *newlistnode;
struct ListNode *curlistnode;
struct ListNode *listhead;

Change it to this

struct ListNode *newlistnode = NULL, *curlistnode = NULL, *listhead = NULL;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...