C++ Logo

std-proposals

Advanced search

C++ showing error even if the code is correct.

From: Shivansh Bhardwaj <shivansh1704bharadwaj_at_[hidden]>
Date: Tue, 26 Jan 2021 21:46:14 +0530
C++ is showing error when 2 nodes are storing address of each other's.

*For example :*
Consider a singly linked list where number of nodes is greater than 3.
Definition for singly-linked list:
  struct ListNode {
     int val;
     ListNode *next;
   };
Now I am writing 2 codes for "reversing the singly linked list" function :
One that is accepted and other one that is showing error for no reason .


 *CORRECT CODE : *
ListNode* reverseList(ListNode* head) {
        ListNode *a,*b,*c;
        a=head;
        if(!a)
            return a;
        b=head->next;
        head->next=NULL;
        while(b!=NULL)
        {
            c=b->next;
            b->next=a;
            a=b;
            b=c;
        }
 return a;
 }

*CODE THAT Is SHOWING ERROR :* For this code I have attached a pdf
named "note" (having 4 nodes) for showing it's working.
 ListNode* reverseList(ListNode* head) {
        ListNode *a,*b,*c;
        a=head;
        if(!a)
            return a;
        a=head->next;
        b=head->next->next;
        while(b!=NULL)
        {
            c=b->next;
            b->next=a;
            a=b;
            b=c;
        }
        head->next=NULL;
        return a;
    }
// Error that is shown by this code : "heap-use-after-free"

So, by above example one can see that there is something unusual that
should be rectify for future generetions.
Please try to understand the above and if you feel any confusion contact me
on "shivansh1704bharadwaj_at_[hidden]".
Thanks.🤗

Received on 2021-01-26 10:16:29