user2073805
user2073805

Reputation: 59

C++ "list iterator not dereferenceable" error

I am trying to write code that will alphabetize strings in a linked list. Here is what I have written:

void main() {
list<string> myList;
list<string>::iterator pos;

string newData;
myList.push_back("Anna");

pos = myList.begin();

for (int i = 0; i < 5; i++){
    cin >> newData;
    while(newData > *pos)
        pos++;

    myList.insert(pos, newData);
}

system("pause");
}

This code compiles fine but I get an error that the list iterator is not dereferenceable when I run it.

I am very new with linked lists and iterators so I really don't know how to fix it. Any help would be greatly appreciated!

Upvotes: 1

Views: 321

Answers (3)

Arun
Arun

Reputation: 20383

While doing pos++, you may reach the end of the list, i.e. pos == myList.end().

At that point, further *pos or pos++ is illegal.

The loop logic need to be revise to avoid such illegal instructions.

Upvotes: 0

Andy Prowl
Andy Prowl

Reputation: 126432

The problem is in this cycle:

while(newData > *pos)
    pos++;

Depending on your input, you might keep increasing pos until you reach the end of the list. At that point, dereferencing it when checking the condition of your while loop causes Undefined Behavior.

To fix your program, rewrite your cycle as follows:

while ((pos != myList.end()) && (newData > *pos))
{
    pos++;
}

P.S.: Also notice, that you most likely want to move the pos = myList.begin(); statement inside the for loop, if your intention is to insert the items in inverse lexicographic order (as it seems to be).

Upvotes: 4

billz
billz

Reputation: 45410

while(newData > *pos)
    pos++;

When pos++, it may points to list::end() and dereference it *pos is undefined behavior.

Your list is not sorted anyway, could just list::push_back

for (int i = 0; i < 5; i++){
    cin >> newData;
    myList.push_back(newData);
}

Then sort it later:

  myList.sort();

Upvotes: 1

Related Questions