C++ : List Seg Fault

65 views Asked by At

Can anyone explain me why does this happened?

When I call member function printEvent() inside the block of if-else,I get the correct output,but when I call printEvent() after the block I get this unknown result.

        list<Event*> currentEvents;
    for (j=1; j <= eventsNum; ++j)
    {   
        Event * newEvent;

        if (isIndividual(inFile)) {
            IndividualEvent newIndi = returnIndi(inFile);
            newEvent = &(newIndi);
            newEvent->printEvent();
        }else {
            TeamEvent newTeam = returnTeam(inFile);
            newEvent = &(newTeam);
            newEvent->printEvent();
        }
        cout << "WHY?" << endl;
        newEvent->printEvent();


        currentEvents.push_back(newEvent);
    }
    TVNode.push_back(newEmission);
}

OUTPUT

<Filiko1>
WHY HERE?
<Filiko1q<15-06-2015,14:00<Athens<0`W                                             ����Athensq<Football<1<0>!0����Footballq<2q<Olympiakos<PSG!
                                                                     ����OlympiakosxW^��DW����PSG^��DWPW�^��DWi�n

The above code is part of a big exercise!

1

There are 1 answers

2
Oleg Andriyanov On

The newEvent after if or else block points to already destructed object, as the object's lifetime is limited by the scope in which it is defined. In your case objects newIndi and newTeam will be destroyed after if-else statement, while newEvent pointer still points at one of them.

See this link to learn about C++ scopes: http://en.cppreference.com/w/cpp/language/scope