Click to See Complete Forum and Search --> : How to delete a pointer


motorizedmedia
February 15th, 2008, 01:07 AM
Having a little trouble deleting a pointer, returns only jumbled up numbers...



void deletefn(nametype *head)
{
int option = 0;
nametype *currptr, *deleteptr;
currptr=head;

while(option!=1 && currptr != NULL)
{
cout<<"\nCurrent product is: "<<currptr->description<<endl;
cout<<"Press 1 to delete this product\n "
<<" 0 to continue: ";
cin>>option;

if(option != 1) currptr=currptr->link;}

if(option == 1)
{
currptr = deleteptr;
delete deleteptr;
deleteptr = NULL;
}

else{cout<<"Could not add node to the link."<<endl;}


}//End of deletefn

Paul McKenzie
February 15th, 2008, 01:17 AM
Having a little trouble deleting a pointer, returns only jumbled up numbers...I only see a single function that returns void.

http://www.parashift.com/c++-faq-lite/how-to-post.html#faq-5.8

Regards,

Paul McKenzie

treuss
February 15th, 2008, 02:07 AM
I don't know, what you are trying to achieve (your code is horribly indented and a function called deletefn that prints out a message "Could not add node to the link." does not make much sense in my mind), but deleteptr remains uninitialized throughout your function, so running delete on it might not have the desired effect.

Most compilers issue warnings in case variables are used uninitialized. Either you did not read them or you should check your compiler settings.

code_carnage
February 15th, 2008, 02:54 AM
deleteptr.

You are effcetively doing something like the following..


Member *deleteptr;

anotherptr = deleteptr; // here deleteptr is uninitialized dangling pointer

delete deleteptr;// deleting a uninitialized pointer invoking undefined behaviour
anotherptr->SomeMethod();//calling a method on a deleted pointer which was an uninitialized pointer// Ofcourse undefined behaviour...