Question

I am iterating through a couple of deques, combining the data into a new container and then using the data later. The problem is that any reference to my iterator value is causing a segmentation fault at some point during the execution of the code. From everything I can find says this should be valid because I don't think I am invalidating the iterator in any way.

vector<char> fileData;
deque<deque <char> >::iterator channel;
deque<char>::iterator channelData;

for(channel=instance.mdata.begin(); channel!=instance.mdata.end(); ++channel)
{
    for(channelData=deque<char>(*channel).begin(); channelData!=deque<char>(*channel).end(); ++channelData)
    {
        fileData.push_back(*channelData);
    }
}
Was it helpful?

Solution

You're copy-constructing the deque here:

channelData=deque<char>(*channel).begin()

Then, you take the begin() iterator, and the deque gets destroyed (invalidating the iterator).

And again here:

    channelData!=deque<char>(*channel).end()

So now, you are comparing two iterators that not only have been invalidated, but you're comparing iterators from two different objects, which you cannot do either. Once an iterator is invalidated, the only legal operation on it is assignment.

You'll have to write the code as follows:

for(channel=instance.mdata.begin();channel!=instance.mdata.end();++channel)
{
    for( channelData=channel->begin();channelData!= channel->end();++channelData)
    {
        fileData.push_back(*channelData);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top