Solved

STL list -- Access Violation on remove() -- WHY?

Posted on 2000-04-20
10
395 Views
Last Modified: 2013-12-14
This is a contrived example from my real program.  I am new
to STL.

Why does this give me an Access Violation in the final
for() loop?  Is there some sort of reset that I am supposed
to call between the loops?  

Later, I want to remove specific entries from the list, display
the list, and when the program exits, I want to prevent the memory leak and delete all the remaining entries.  





// stllisttest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iomanip.h>
#include <list>
using namespace std;

class CData {
public:
      int x;
      int y;
};

typedef list<CData*> DATALIST;

int main(int argc, char* argv[])
{
      CData* pData;
      DATALIST dataList;
      DATALIST::iterator i;
      int n;

      for (n = 0; n < 10; n++)
      {
            pData = new CData();
            pData->x = n;
            pData->y = n * n;;

            dataList.insert(dataList.end(), pData);
      }
      
      for (i = dataList.begin(); i != dataList.end(); i++)
      {
            CData* pData = *i;
            cout << "x=" << pData->x << ", y=" << pData->y << endl;
      }

      for (i = dataList.begin(); i != dataList.end(); i++)
      {
            CData* pData = *i; // why does this fail with Access Violation on this line?
            dataList.remove(pData);
            delete pData;
      }

      return 0;
}

0
Comment
Question by:alfredj
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 2
10 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 2736115
Your problem seems to be the call to 'list::remove()':

"list::remove
void remove(const T& x);
The member function removes from the controlled sequence all elements, designated by the iterator P, for which *P == x."

If you want to remove a single list element, use 'list::erase()' instead, e.g.


for (i = dataList.begin(); i != dataList.end(); i++)
{
CData* pData = *i;
dataList.erase(pData);
delete pData;
}



0
 

Author Comment

by:alfredj
ID: 2736136
Okay, so I guess I do not understand the documentation.

Does remove() remove EVERYTHING IN THE LIST?  What does "removes from the controlled sequence all elements, designated by the iterator P, for which *P == x" mean (in English? German?)
Thanks, if this works, I'll happily give the points.
0
 

Author Comment

by:alfredj
ID: 2736146
BTW, the line...

dataList.erase(pData);

....does not compile, so I changed it to...

dataList.erase(i);

....and that compiles, but fails on the second iteration thru the loop instead of the first.

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:jkr
ID: 2736148
Is' schwer zu sagen, ich hätte auch erst 'alle' verstanden ;-)
0
 
LVL 86

Expert Comment

by:jkr
ID: 2736153
Well, to be honest, I'd usually use a construct like that:

for (i = dataList.begin(); i != dataList.end(); i++)
{
delete (*i);
}

dataList.clear();
0
 

Author Comment

by:alfredj
ID: 2736189
Okay, that's cool, but I do need to
delete a single item in the list (as a result of the user's action) then write the remaining data to a database and delete the remaining items in the list (to prevent the memory leak).

0
 

Author Comment

by:alfredj
ID: 2736199
So I added a loop like this, but it fails on the second iteration.  Is it illegal to change the list when you are iterating thru it?

-Alfred


      for (i = dataList.begin(); i != dataList.end(); i++)
      {
            CData* pData = *i; // fails here on the second iteration
            if (pData->x == 4)
            {
                  cout << "DELETING: x=" << pData->x << ", y=" << pData->y << endl;
                  dataList.erase(i);
                  //delete (*i);
            }
      }
0
 
LVL 3

Accepted Solution

by:
GlennDean earned 100 total points
ID: 2736218
Hi alfredj:
   You are removing an element, then trying to use the iterator to move to the next (but the iterator points to a non-existing element.
for (i = dataList.begin(); i != dataList.end(); )
{
CData* pData = *i;
i++; //move to an existing element
dataList.remove(pData);
delete pData;
}
   Glenn


0
 

Author Comment

by:alfredj
ID: 2736272
Okay, this works.  Explain the difference between .remove() and .erase() and you get an 'A'

0
 
LVL 3

Expert Comment

by:GlennDean
ID: 2736336
erase deletes a particular element while remove deletes all the elements equal to a particular value.  In your case, each time you called remove it deleted one item because only 1 element had a value identical to the pointer.
   Glenn
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
thread-safe code in c++ 2 128
Dynamically allocate memory 9 76
Dialogbox API leak? 18 119
operator overload: incompatible type and too many params 5 99
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
How to install Selenium IDE and loops for quick automated testing. Get Selenium IDE from http://seleniumhq.org Go to that link and select download selenium in the right hand columnThat will then direct you to their download page.From that page s…
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question