Adroit
Adroit

Reputation: 721

Vector push_back causing Unhandled exception

Everything is working until the compiler tries to perform the push_back operation. in the if condition proper values are being returned.
I have declared items as:

vector<int> items; // inside the header file.

//inside the .cpp file

void MsPs::findnSort()
{
    for(int i = 1; i<50 ; i++)
    {

        string temp = static_cast<ostringstream*>( &(ostringstream() << i) )->str();    // TO convert int i to a string temp
        if(findSupport(temp) >= MIS[i])
        {
            items.push_back(i);
        }

    }

}

the following error pops up:

Unhandled exception at 0x5052ad4a (msvcp100d.dll) in PrefixScan.exe: 0xC0000005: Access violation reading location 0x3d4cccd1.

PS: I have one more function using the push_back operation and there it's working fine.

Can anyone help me with this?

Even this gives the same error:

void MsPs::findnSort()
{
    for(int i = 1; i<50 ; i++)
    {

        items.push_back(i);
    }


}

Upvotes: 2

Views: 2018

Answers (1)

Chris Hayden
Chris Hayden

Reputation: 1144

I think the issue is that the ostringstream is destructed when the static cast returns. Thus your pointer is dangling when str() is called. Try this instead:

void MsPs::findnSort()
{
    for(int i = 1; i<50 ; i++)
    {
        ostringstream blah;
        string temp = (blah << i).str();

        if(findSupport(temp) >= MIS[i])
        {
            items.push_back(i);
        }

    }

}

Upvotes: 2

Related Questions