tags:

views:

361

answers:

3

I have a program which is like this

list<int>:: iterator n = alist.begin();
while(n!= (list<int>::iterator)0)
{
    printf("Element is %d\n",*n);
    n = alist.erase(n);
}

So here i am comparing iterator with zero. but after deleting the last element the compiler is showing this error.

*** glibc detected *** ./new: free(): invalid pointer: 0xbf99cb10 ***
======= Backtrace: =========
/lib/libc.so.6[0xb7d956e1]
/lib/libc.so.6(cfree+0x89)[0xb7d96d79]
/usr/lib/libstdc++.so.6(_ZdlPv+0x21)[0xb7f3ff81]
./new[0x8048c81]
./new[0x8048ca6]
./new[0x8048d07]
./new[0x8048d39]
./new(__gxx_personality_v0+0x216)[0x804888e]
/lib/libc.so.6(__libc_start_main+0xdc)[0xb7d46f9c]
./new(__gxx_personality_v0+0x49)[0x80486c1]
======= Memory map: ========
08048000-0804a000 r-xp 00000000 08:09 3704751    /home/sathya/chaithra/archivesthrash/new

If I want the iterator to be zero if the queue/list is empty.. what i should do? Because in my project I need to compare this iterator with zero only and not with alist.end().. What may be the probable solution to this...?

+8  A: 

Why do you think the iterator will ever "be zero"? Iterators are not pointers or indexes. If you need to check if a container is empty, use the empty() member function.

anon
+3  A: 

Change this to

list<int>:: iterator n = alist.begin();
while(n!= alist.end())
{
    printf("Element is %d\n",*n);
    n = alist.erase(n);
}

or

list<int>:: iterator n = alist.begin();
while(alist.size() > 0)
{
    printf("Element is %d\n",*n);
    n = alist.erase(n);
}

because you must not compare an iterator to NULL - that's not a defined state for an iterator.

Stefan
Second one is very bad - size() is allowed to be O(N) for lists. Use empty() anywhere you compare size() to 0.
Greg Rogers
+1  A: 

Maybe you want to test whether the content of the iterator is 0. In this case... you need to change to something like:

list<int>::iterator n = alist.begin();
while( !alist.empty() && 0 != *n) 
{
    printf("Element is %d\n",*n);
    n = alist.erase(n);
}
Cătălin Pitiș