The following code stops working, shows an empty screen, shows a number, and then prints an error message that code stopped working.
#include <iostream>
using namespace std;
class Link{
public:
long ddata;
Link *next;
Link(long d){
ddata=d;
}
void displaylin(){
cout<<ddata<<" "<<endl;
}
};
class firstlast{
private :
Link *first;
Link * last;
public:
firstlast(){
first=NULL;
last=NULL;
}
bool empthy(){
return (first==NULL);
}
void insertfirst(long dd){
Link *newlink=new Link(dd);
if (empthy())
last=newlink;
newlink->next=first;
first=newlink;
}
void insertlast(long dd){
Link *newlink=new Link(dd);
if ((empthy()))
first=newlink;
else
last->next=newlink;
newlink=last;
}
long deletefirst(){ //delete first link
long temp=first->ddata;
if (first->next==NULL)//only one item
last=NULL;
first=first->next;
return temp;
}
void displayList(){
cout<<"first -> last "<<endl;
Link *current=first;
while(current!=NULL){
current->displaylin();
current=current->next;
}
}
};
int main(){
firstlast *fl=new firstlast();
fl->insertfirst(22);
fl->insertfirst(44);
fl->insertfirst(66);
fl->insertlast(33);
fl->insertlast(88);
fl->insertlast(100);
fl->deletefirst();
fl->displayList();
return 0;
}
I think somewhere is is overflow, but I can’t find where. IDE One shows the output of my program.
The problem is this line in
insertlast(long):It should be:
With that change, the output becomes:
EDIT: As @Jared pointed out, your code suffers from memory leaks. This happens whenever you allocate heap memory with
newormallocbut do not free it with the corresponding “free” function.It is important that each pointer returned by
newbe freed exactly once bydelete. If you fail to calldelete, then your program leaks memory. If you calldeletemore than once to “double free” a region, then your program invokes Undefined Behavior.In this code:
notice that
first=first->next;makes you lose the pointer to a piece of dynamically-allocated memory. Remember thatfirstwas set to the result ofnew, so you need todelete firstbefore overwritingfirstwith a pointer to a different region of dynamically-allocated memory.Also, you need to add to your class:
deletefirst().firstlastinstances.operator=(const firstlast& fl), that also makes a deep copy.