473,662 Members | 2,588 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Crash while erasing a member in a vector

Hello,

I am facing a starnge problem while erasing the last member in a
vector. I am using VC++ .NET 2002 complier. I have vector of
CComPtr<..> (irrelevant here), and then I iterate over the vector. If
it is the iterator, then I remove the element from the vector using
vecObjects.eras e(it). It works fine till the last element. While
removing the last element it throws exception and fails. But the same
vecObject.clear () works with out any problem. Can somebody there,
please help me to indentify this problem and solution to this

Thanks in advance.
EK

Dec 21 '05 #1
11 4350
In article <11************ **********@z14g 2000cwz.googleg roups.com>,
<ee****@gmail.c om> wrote:
I am facing a starnge problem while erasing the last member in a
vector. I am using VC++ .NET 2002 complier. I have vector of
CComPtr<..> (irrelevant here), and then I iterate over the vector. If
it is the iterator, then I remove the element from the vector using
vecObjects.era se(it). It works fine till the last element. While
removing the last element it throws exception and fails. But the same
vecObject.clea r() works with out any problem. Can somebody there,
please help me to indentify this problem and solution to this


You are most likely going off the end of the vector and erasing an
invalid iterator. Please post a code snippet that can compile and
you'll get much better responses.
--
Mark Ping
em****@soda.CSU A.Berkeley.EDU
Dec 21 '05 #2
Yes, the 'last' position in a vector is one beyond the last element.

If you are progressing through your vectory array, check if the address
of the iterator has reached the address of the last position. See the
code example below.

vector<int>::it erator iter = 0;
for( iter = vecList.begin() ; iter != vecList.end(); iter++ )
{
delete *iter;
}

Dec 21 '05 #3

"Jordan" <jo***********@ gmail.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
Yes, the 'last' position in a vector is one beyond the last element.

If you are progressing through your vectory array, check if the address
of the iterator has reached the address of the last position. See the
code example below.

vector<int>::it erator iter = 0;
for( iter = vecList.begin() ; iter != vecList.end(); iter++ )
{
delete *iter;
}


That's how to delete dynamically allocated objects from a vector, but the
iterator you've declared refers to a vector that does not have pointers, it
has just int's. You don't want to delete an int, or anything that was not
created via new. (I know, it's just an example, but it's a bad example.
:-))

The OP asked about using erase() to remove items from a vector. That's
different from deleting the dynamically allocated data pointed to by
pointers stored in the vector. And without seeing his code, we can't say
_for_sure_ what the problem is. My "guess" is that clear() will work fine,
but it's just a guess at this point. Only if he also wants to delete
dynamically allocated objects will he first want to have a loop like the one
you've shown.

-Howard

Dec 21 '05 #4

ee****@gmail.co m wrote in message
<11************ **********@z14g 2000cwz.googleg roups.com>...
Hello,

I am facing a starnge problem while erasing the last member in a
vector. I am using VC++ .NET 2002 complier. I have vector of
CComPtr<..> (irrelevant here), and then I iterate over the vector. If
it is the iterator, then I remove the element from the vector using
vecObjects.era se(it). It works fine till the last element. While
removing the last element it throws exception and fails. But the same
vecObject.clea r() works with out any problem. Can somebody there,
please help me to indentify this problem and solution to this
Thanks in advance.
EK
You forgot to show the code! Are you trying to do this in a loop?

If you do:
vecObjects.eras e(it);
....then iterator 'it' may no longer be valid [1]. Reset it.
... It works fine till the last element.

Use:
vecObjects.pop_ back(); // Removes the last element.

[1] " A vector's iterators are invalidated when its memory is reallocated.
Additionally, inserting or deleting an element in the middle of a vector
invalidates all iterators that point to elements following the insertion or
deletion point. ..."

--
Bob R
POVrookie
Dec 21 '05 #5
<ee****@gmail.c om> schrieb im Newsbeitrag
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
Hello,

I am facing a starnge problem while erasing the last member in a
vector. I am using VC++ .NET 2002 complier. I have vector of
CComPtr<..> (irrelevant here),
Perhaps it is irrelevant for your problem, but you should not put instances
of CComPtr into C++ containers. Some of these containers (or some
implementations of them) do not work well with objects overloading
operator&.
and then I iterate over the vector. If
it is the iterator, then I remove the element from the vector using
vecObjects.eras e(it).


When you iterate through a container and try to erase its last element, make
sure not to increment the iterator after erasing. Actually you should never
increment an iterator after erasing the element it refers to. For all
containers, all iterators refering to the erased element become invalid. So
don't do something like this

for (SomeContainer: :iterator it = myContainer.beg in(); it !=
myContainer.end (); ++it)
{
if (RemoveThisElem ent(*it)) myContainer.era se(it);
}

If SomeContainer is an std::vector, this seems to work until you try to
erase the last element, but actually it will not examine those elements
imediately following an element, that will be removed. Now if you erase the
last element, end() will change (in some implementations end() will become
equal to the iterator for the erased elemet) and due to the final increment
the test for equality to end() will fail and the loop will continue until it
reaches the end of allocated memory. (Or it will behave entirely different,
after all that's the problem with undefined behaviour.)

HTH
Heinz
Dec 21 '05 #6
In article <43************ **********@news read2.arcor-online.net>,
Heinz Ozwirk <ho**********@a rcor.de> wrote:
for (SomeContainer: :iterator it = myContainer.beg in(); it !=
myContainer.en d(); ++it)
{
if (RemoveThisElem ent(*it)) myContainer.era se(it);
}

If SomeContainer is an std::vector, this seems to work until you try to
erase the last element, but actually it will not examine those elements
imediately following an element, that will be removed.


This is actually worse, because as you remove the elements you
invalidate your iterator, so your "++it" is a very bad thing.

Better is:

vector<int> container;
vector<int>::it erator iter;
for (iter=container .begin(); iter != container.end() ; )
{
if (RemoveThisElem ent(*iter)) {
iter = container.erase (iter);
} else {
++iter
}
}

Note the assignment of "iter" from erase, and the lack of ++iter in
the for loop. Either the iter is manually incremented or the erase
operation leaves it pointing to the next position.
--
Mark Ping
em****@soda.CSU A.Berkeley.EDU
Dec 21 '05 #7
Hello All,

Thanks for the huge response, I have got. I am yet to try the
suggestions. In the mean time I am adding the code snippet here for
better clarity of the question I have asked.

Though I cannot reproduce the code, it looks similar to this.

I have a vector vecObjects with CComPtr<Interfa ces I..>. Now I have to
check the contents for this vector for some conditions. Hence I iterate
the container as follows.

std::vector< CComPtr<I..> >::iterator it = vecObjects.begi n();
std::vector< CComPtr<I..> >::iterator itEnd = vecObjects.end( )

for(;it != itEnd; ++it); // I tried post increment also
{
// Check the iterator for some conditions
if (! IsValid(*it))
{
vecObjects.eras e(it); // This causes the crash with the last
element
}
++it;
}

// At the same time the following code works

for(;it != itEnd; ++it); // I tried post increment also
{
// Check the iterator for some conditions
if (! IsValid(*it))
{
if(vecObjects.s ize() == 1)
vecObjects.clea r();
else
vecObjects.eras e(it);
}
++it;
}

Thank you for all the help.
EK

Dec 22 '05 #8
In article <11************ *********@o13g2 000cwo.googlegr oups.com>,
<ee****@gmail.c om> wrote:
std::vector< CComPtr<I..> >::iterator it = vecObjects.begi n();
std::vector< CComPtr<I..> >::iterator itEnd = vecObjects.end( )

for(;it != itEnd; ++it); // I tried post increment also
{
// Check the iterator for some conditions
if (! IsValid(*it))
{
vecObjects.eras e(it); // This causes the crash with the last
element
}
++it;
}
Yeah, this is broken.
// At the same time the following code works No it doesn't.
for(;it != itEnd; ++it); // I tried post increment also
{
// Check the iterator for some conditions
if (! IsValid(*it))
{
if(vecObjects.s ize() == 1)
vecObjects.clea r();
else
vecObjects.eras e(it);
}
++it;
}


the 'erase' invalidates all the iterators. You can't cache the 'end'
iterator. Furthermore, you need to use the return value of erase,
since you just invalidated 'it' when you erased it (and hence
incrementing it is unsafe).
--
Mark Ping
em****@soda.CSU A.Berkeley.EDU
Dec 22 '05 #9
On 21 Dec 2005 17:01:17 -0800, ee****@gmail.co m wrote:
Hello All,
(...)
std::vector< CComPtr<I..> >::iterator it = vecObjects.begi n();
std::vector< CComPtr<I..> >::iterator itEnd = vecObjects.end( )

for(;it != itEnd; ++it); // I tried post increment also
{
// Check the iterator for some conditions
if (! IsValid(*it))
{
vecObjects.eras e(it); // This causes the crash with the last
element
}
++it;
}

(...)

From the code you show us, I think the best soultion is to use the
algorithm std::remove_if using as predicte a functor written around
IsValid.

std::vector<... >::iterator lastPosition=
std::remove_if( vecObjectsbegin (),vecObjects.e nd(),wrapIsVali d());
vecObjects.eras e(lastPosition, vecObjects.end( ));

Or something similar.

Best regards,

Zara
Dec 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2202
by: Generic Usenet Account | last post by:
To settle the dispute regarding what happens when an "erase" method is invoked on an STL container (i.e. whether the element is merely removed from the container or whether it also gets deleted in the process), I looked up the STL code. Erase certainly does not delete the memory associated with the element. However, it appears that the destructor on the element is invoked. I wonder why it has to be this way. In my opinion, this renders...
10
3082
by: dalbosco | last post by:
Hello, I am new to STL and I've written the following code which crash. Could anyone tell me why this code crash? Thanks by advance. -- J-F #include <iostream>
18
2555
by: Active8 | last post by:
I put the bare essentials in a console app. http://home.earthlink.net/~mcolasono/tmp/degub.zip Opening output.fft and loading it into a vector<float> screws up, but input1.dat doesn't. It does load the vector, too. It just craps out when you return to the console, or in a Windows app, the message loop. I think it has something to do with the vector<float> going out of scope and trying to free memory, but don't know why it would do...
2
3187
by: laniik | last post by:
Hi. For some reason I am getting a crash on pop_back() and Im not sure why. sorry I cant post the whole code because the vector is used in a bunch of places. i have a vector<bool> complete;
5
12057
by: ma740988 | last post by:
For starters, Happy New Year to all!! I created a vector of pairs where pair first is a primitive and pair second is a vector of ints. So now: # include <iostream> # include <vector>
13
6394
by: mahajan.vibhor | last post by:
I have a list of pointers. e.g A* a = new A(); // A is a class stl::list<A*list_a; I am inserting object of class in the after allocating memeory thru new operator. But when i want to erase all elements from the list. my progam crashes. I delete element by using a iterator.
5
6784
by: cbbibleboy | last post by:
Hey, I've been getting some very strange results with what seems to be very simple code. All I'm doing is trying to use an STL vector of "cSprite"s -- a class I wrote. The problem arises when I try to resize the vector either explicitly through the "resize" method, or implicitly through the "push_back". Everything compiles fine, but the program crashes upon calling of the methods. If I instead make it a vector of "int"s it can resize, but still...
3
6185
by: =?iso-8859-1?q?Erik_Wikstr=F6m?= | last post by:
I have some code where there's this vector of pointers to objects and I need to delete and erase some of them, the problem is that to know which I need to iterate through the vector and I'm trying to do this as efficient as possible. The code is something like this: struct Thing { int value; Thing* ptr; Thing() : ptr(0) { } };
4
2973
by: Rakesh Kumar | last post by:
Hi All - In a project of mine - I was trying to scale down the actual issue to the following piece of code. I need to allocate an array of strings and reserve the individual string to a particular size (4K) . I wrote 2 functions - allocVectorOfStrings() and allocArrayOfStrings(). Each of them seem to allocate similar amounts of memory - but the version of vectorOfStrings seem to crash with the following error - "double free or corruption...
0
8432
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8344
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8546
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7367
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6186
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5654
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4347
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.