0

This is my first time trying to use STL and lists, and the problem here should be in the removeOdds function, when I test it on g++ it revealed memory leak:

#include <list>
#include <vector>
#include <algorithm>
#include <iostream>
#include <cassert>
using namespace std;

  // Remove the odd integers from li.
  // It is acceptable if the order of the remaining even integers is not
  // the same as in the original list.
void removeOdds(list<int>& li)
{
    for(list<int>::iterator p = li.begin(); p != li.end(); p++)
        if(*p % 2 != 0)
            li.erase(p);
}

void test()
{
    int a[8] = { 2, 8, 5, 6, 7, 3, 4, 1 };
    list<int> x(a, a+8);  // construct x from the array
    assert(x.size() == 8 && x.front() == 2 && x.back() == 1);
    removeOdds(x);
    assert(x.size() == 4);
    vector<int> v(x.begin(), x.end());  // construct v from x
    sort(v.begin(), v.end());
    int expect[4] = { 2, 4, 6, 8 };
    for (int k = 0; k < 4; k++)
        assert(v[k] == expect[k]);
}

int main()
{
    test();
    cout << "Passed" << endl;
}
LHC2012
  • 187
  • 6
  • 1
    You should read the documentation of the `erase` method carefully. It invalidates the passed-in iterator, so continuing to use that iterator will give you problems. http://www.cplusplus.com/reference/list/list/erase/ – nneonneo Feb 17 '20 at 04:02
  • Thank you for observing this. I tried p=li.erase(p) to solve this, but is this the conventional solution? – LHC2012 Feb 17 '20 at 04:05
  • Mostly, but you have to be sure not to increment the iterator if you erase (since the iterator produced is already the next one). One approach is just to move the p++ into an else-branch instead of doing it each time in the for loop. – nneonneo Feb 17 '20 at 04:08
  • @nneonneo Actually for my code, I tried to run with saying p=li.erase(p); inside the for loop and somehow it still passed the test. I thought it will fail at the "7, 3" part of the list because it should skip over the 3? – LHC2012 Feb 17 '20 at 04:14

0 Answers0