Han Kenny Han Kenny - 3 months ago 15
C++ Question

Delete node wont work

I'm trying to delete a node on a linked list but after the delete command I tried to display the data inside the node and I could still display the supposedly deleted data. Search is the node im trying to delete

int position=0;
while(admintemp !=NULL)
{
position=position+1;
if(admintemp==search)
{
cout<<"found"<<position;
getch();
break;

}
admintemp = admintemp->next;
}


node *body = new node;
node *admintemp = new node;
if(position>0)
{
admintemp = adminhead;

for (int i= 1;i<position;i++)
{
body = admintemp;
admintemp = admintemp->next;
}
body->next=admintemp->next;
cout<<"deleting";
getch();
delete admintemp;
}

Answer

Reading data via a deleted pointer is "Undefined Behaviour" - meaning that the compiler can do what it pleases and your program has no meaning.

You may get the results you expect, you may get a crash, you may get demons flying out your nose. There is no way to tell. The program is simply invalid and any behaviour is OK. As per the rules of the C++ standard it is the programmers responsibility to not invoke undefined behaviour - it may compile and run, but you've broken the rules so the compiler has no obligation to do anything sane (or even anything at all).

Comments