C++ linked list user input out of bound validation causes program to end

I have a delete node based on position function and I am trying to do validation with the logic that the user input will repeat itself whenever the user's input is larger than the linked list size or in other words out of bound.

I declared int size and it'll increment itself whenever a new node is created, vice versa for remove node. Here is my remove node function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
     void delete_position(int pos) //delete node with given position
    {
        node *current=new node;
        node *previous=new node;
        current=head;

        if(head==NULL)
        {
            cout<<"You haven't ordered any cake(s)"<<endl;
        }

        for(int i=1;i<pos;i++)
        {
            previous=current;
            current=current->next;
        }
        previous->next=current->next;

        if(pos == 1){
            node *temp=new node;
            temp=head;
            head=head->next;
            delete temp;
        }
        size--;
    }


Here is my validation, I used a do while loop to check the user's input, so whenever the input is larger than the size, it'll loop the user input once again. The problem is, say there are only 2 nodes in my list and I enter 4, the program jumps to the next line and ends.

1
2
3
4
5
6
7
8
9
10
cout<<"====destroy node===="<<endl;
cout<<"Which cake would you like to destroy?"<<endl;

do{

cin>>destroy_input;

}while(destroy_input > size);

list.delete_position(destroy_input);


Here is my full code in pastebin: https://pastebin.com/vfuRYMLk
Last edited on
a debugging technique that I have found critical for decades is to trust nothing and believe nothing.
so what I want you to do is change your code to this and run it:

1
2
3
4
5
6
7
do{
cout << "*  size = " << size << endl;
cin>>destroy_input;

}while(destroy_input > size);

list.delete_position(destroy_input);


if size is really 2 and you put in 4, we have something really messed up going on here. the * is to make it stand out in the program spew and to make it easy to find later if you forget to take it out.
Last edited on
You leak memory at lines 3, 4, and 20. And if you delete anything other than the first element, you leak the deleted element too.
Topic archived. No new replies allowed.