Puzzle

Discussion in 'C++' started by nrivera.eng, Aug 1, 2005.

  1. nrivera.eng

    nrivera.eng Guest

    Gurus,

    This is the problem:

    The code below outputs bogus data when the either: *( iter->second )
    is used and causes a segfault or *(tools[iter->first]) is used the
    curious things is that the output of iter->first is perfect and when
    the input is verified by:

    for(int i = 0 ; inventory && !inventory.eof(); i++ )
    {
    Tool tempTool;
    inventory >> tempTool;

    tools.insert( Record::value_type( tempTool.getRecordNum(),
    &tempTool ) );

    cout << *(tools[tempTool.getRecordNum()]); // Input verification
    }

    The data seems to be correctly input into the Map data structure so
    WHY THE BOGUS OUTPUT and the SEGFAULT?

    Here is the Output portion:

    for( Record::const_iterator iter = tools.begin(); iter !=
    tools.end();
    ++iter)
    {
    cout << *(tools[iter->first])<< endl;
    }

    were Record is:

    typedef map < int, Tool *, less< int > > Record;

    and Tools is a ( int, string, int, double ) object

    the << operator has been overloaded and verified.

    Thanks,
    Noel
     
    nrivera.eng, Aug 1, 2005
    #1
    1. Advertisements

  2. * :
    Address of local variable.
     
    Alf P. Steinbach, Aug 1, 2005
    #2
    1. Advertisements

  3. So, your 'tools' is defined to contain _addresses_, right? You're storing
    the address of a local variable on every loop. Don't. Make your 'tools'
    map contain the _objects_ instead.
    Because as soon as the body of this loop finishes, the address you store
    in the map becomes _invalid_.
    Make it

    typedef map<int,Tool> Record;

    and when inserting, do

    tools[tempTool.getRecordNum()] = tempTool;

    or

    tools.insert(make_pair(tempTool.getRecordNum(), tempTool));
    V
     
    Victor Bazarov, Aug 1, 2005
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.