473,769 Members | 5,787 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Segmentation fault calling insert on vector

Consider the following code:
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int
main()
{
vector<stringwl ;

vector<string>: :iterator it = wl.begin();
string w;

while(cin >w)
{
wl.insert(it++, w);
cout << "inserted successfully" << endl;
}
}

It crashes after one succesful insert it seems. I know I can solve it
using push_back or push_front, but I'm looking at a bigger program that
uses inserts exclusively and doesn't crash...In the real program I dont
want to add elements to the front or the back

Sep 7 '06 #1
6 6558
Eric Lilja wrote:
Consider the following code:
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int
main()
{
vector<stringwl ;

vector<string>: :iterator it = wl.begin();
string w;

while(cin >w)
{
wl.insert(it++, w);
cout << "inserted successfully" << endl;
}
}

It crashes after one succesful insert it seems. I know I can solve it
using push_back or push_front, but I'm looking at a bigger program
that uses inserts exclusively and doesn't crash...In the real program
I dont want to add elements to the front or the back
'it' is most likely invalid after you insert. If you try using it (and
incrementing constitutes using), you get undefined behaviour.

You probably meant

it = wl.insert(it, w); ++it;

Here, 'it' returned from 'insert' is the iterator to the newly inserted
element. If you need the next one, increment it.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Sep 7 '06 #2
Eric Lilja wrote:
Consider the following code:
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int
main()
{
vector<stringwl ;

vector<string>: :iterator it = wl.begin();
string w;

while(cin >w)
{
wl.insert(it++, w);
cout << "inserted successfully" << endl;
}
}

It crashes after one succesful insert it seems. I know I can solve it
using push_back or push_front, but I'm looking at a bigger program that
uses inserts exclusively and doesn't crash...In the real program I dont
want to add elements to the front or the back
Two problems. First, std::vector::in sert() invalidates all interators,
but returns a valid iterator. That means if you continue to use the
old iterator - as you do - you are invoking undefined behavior - in
this case, a crash. Second, as a conceptual matter,
std::vector::in sert() inserts BEFORE the iterator. You set the
iterator to begin(), so conceptually this is wrong (because you don't
want to insert BEFORE begin()), even though this will work in practice
(because for an empty vector, begin()==end()) .

So, I would change your program as follows:

int main()
{
vector<stringwl ;
vector<string>: :iterator it = wl.end();
// note change in above line
string w;
while(cin >w) {
it = wl.insert(it, w);
// note change in above line
cout << "inserted successfully" << endl;
}
}
Best regards,

Tom

Sep 7 '06 #3

Victor Bazarov wrote:
Eric Lilja wrote:
Consider the following code:
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int
main()
{
vector<stringwl ;

vector<string>: :iterator it = wl.begin();
string w;

while(cin >w)
{
wl.insert(it++, w);
cout << "inserted successfully" << endl;
}
}

It crashes after one succesful insert it seems. I know I can solve it
using push_back or push_front, but I'm looking at a bigger program
that uses inserts exclusively and doesn't crash...In the real program
I dont want to add elements to the front or the back

'it' is most likely invalid after you insert. If you try using it (and
incrementing constitutes using), you get undefined behaviour.

You probably meant

it = wl.insert(it, w); ++it;
Right! I forgot that insert() returns a valid iterator! It worked in
the larger program because in that one a separate function was called
for each insert() that obtained a fresh iterator for each time it was
called. Thanks for the quick reply.
>
Here, 'it' returned from 'insert' is the iterator to the newly inserted
element. If you need the next one, increment it.

V
Eric

Sep 7 '06 #4
Thomas Tutone wrote:
[..] First, std::vector::in sert() invalidates all
interators, [..]
Actually, 'insert' only invalidates iterators if reallocation
happens. You can prevent that by using 'reserve'.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Sep 7 '06 #5
Victor Bazarov wrote:
Thomas Tutone wrote:
[..] First, std::vector::in sert() invalidates all
interators, [..]

Actually, 'insert' only invalidates iterators if reallocation
happens. You can prevent that by using 'reserve'.
Now, I know that generally when one argues with Victor Bazarov in the
context of C++, chances are high that one is wrong and Victor is right.
But I think in this case, you are partially incorrect. (And I think
my answer was partially incorrect as well.)

I said that insert invalidates all interators. You said that insert
invalidates iterators _only_ if reallocation happens. I don't have my
copy of Josuttis (or the Standard) handy, but both Dinkumware and SGI
state:

"If no reallocation occurs, iterators become invalid only from the
point of insertion through the end of the sequence."

Thus, I think it is accurate that some - but not all - iterators do
become invalid. In the OP's example, he continues to use the iterator,
which is at the point of insertion. I believe that iterator is
invalid, regardless of whether reallocation occurs.

So - I acknowldege that my statement that _all_ iterators are
invalidated was overbroad. But I think your correction was similarly
inaccurate. Please correct me if I've misunderstood.

Best regards,

Tom

Sep 7 '06 #6
Thomas Tutone wrote:
Victor Bazarov wrote:
>Thomas Tutone wrote:
>>[..] First, std::vector::in sert() invalidates all
interators, [..]

Actually, 'insert' only invalidates iterators if reallocation
happens. You can prevent that by using 'reserve'.

[..]
I said that insert invalidates all interators. You said that insert
invalidates iterators _only_ if reallocation happens. I don't have my
copy of Josuttis (or the Standard) handy, but both Dinkumware and SGI
state:

"If no reallocation occurs, iterators become invalid only from the
point of insertion through the end of the sequence."
[..]
The Standard says that iterators before the point of insertion remain
valid if no reallocation occurs. You're right, some do become invalid.
In practice they probably simply point to different elements. But who
cares about what's in practice? :-)

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Sep 7 '06 #7

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

Similar topics

9
3186
by: fudmore | last post by:
Hello Everybody. I have a Segmentation fault problem. The code section at the bottom keeps throwing a Segmentation fault when it enters the IF block for the second time. const int WORDS_PER_LINE = 4; when counter == 7 is when the string Concatenation fails within the IF block.
3
6579
by: VB | last post by:
Hi, here File.cpp and File.h: File.cpp: ---------------------- #pragma warning (disable: 4786)
1
1821
by: sandwich_eater | last post by:
I get a segmentation fault in my program when calling a function "TestFn" that has been passed as a pointer into another function. The following excerpt should give enough information as to what I am doing wrong... typedef void TIdxMultiFunc (int i, std::vector<double> f); void TestFn(int i, std::vector<double> f) { double t; // execution does not get this far
7
3026
by: silverburgh.meryl | last post by:
Hi, I have a C++ problem which uses STL containers and algorithm and it has a segmentation fault under some condition. Here is a back trace from gdb. Is it possible to tell what is wrong from the trace? I know which method is crashing (MyHandler.cpp:133), but I don't know why. Thanks for any help.
5
6753
by: silverburgh.meryl | last post by:
Hi, I have a segmentation fault in line 66 of GroupResult.h and I can't figure out why that causes any problem, I appreciate if anyone can help. line 66 of Result.h: 66 size_t size() const { return _bdl.size(); }
2
2242
by: zl2k | last post by:
hi, all I am using a 2 dimensioanl array implemented by vector<vector<long> >. When the row number grows to 8 and I am trying to insert a new row, I got the segmentation error. However, if I reserve the row number to 16 (in my case the size of row will always less than 16) at the very begining, then everything works well. (The column number could be quite large.) What is the problem? The vector can automatically grow as needed, right?...
2
456
by: Chris | last post by:
I'm compiling the following code with GCC 4.1.0 (on fedora 6 I think). It compiles fine, then when I run it it simply prints "segmentation fault". int main() { vector<vector<string yo; yo = "hello"; cout << yo; return 0; }
8
14700
by: Bryan | last post by:
Hello all. I'm fairly new to c++. I've written several programs using std::vectors, and they've always worked just fine. Until today. The following is a snippet of my code (sorry, can't include all of it- it's over 1k lines long). In addition, I'm including an "include" file where structures like "stack" are defined. Again, it's really long. I doubt the problem lies there, though, because the include file is used in many other...
2
3311
by: Steve | last post by:
I have segmentation fault when calling resize on an stl vector. I'm unsure if I'm doing something horribly wrong or if the stl is being dumb. The code breaks down like this: ------------------------------------- class Device { public: Device() { m_isBusy = false;
0
10039
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9990
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
9860
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
8869
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
7406
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
6668
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
5297
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5445
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3560
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.