C++:列出赛格故障

C++ : List Seg Fault

本文关键字:故障 C++      更新时间:2023-10-16

谁能解释我为什么会这样?

当我在 if-else 块内调用成员函数 printEvent() 时,我得到了

正确的输出,但是当我在块之后调用 printEvent() 时,我得到了这个未知的结果。

        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);
}

输出

<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

上面的代码是一个大练习的一部分!

if or else block 后面的newEvent指向已销毁的对象,因为对象的生存期受定义对象的范围限制。在您的情况下,对象 newIndinewTeam 将在 if-else 语句后被销毁,而指针仍指向其中一个newEvent

请参阅此链接以了解C++范围:http://en.cppreference.com/w/cpp/language/scope