简体   繁体   中英

missing cout before segmentation fault

I had a segmentation fault in my code, so I put many cout on the suspicious method to localise where.

bool WybierajacyRobot::ustalPoczatekSortowania(){
    cout << "ustal poczatek sortowania: " << poczatekSortowania << endl ;
    list< Pojemnik >::iterator tmp;
    cout << "LOL"; // <-- this cout doesn't print when segfault

    if (!poczatekSortowania){   // <- T1
        cout << "first task" ;
        tmp = polka.begin();
    }
    else{   // <-- T2
        cout << " second task " ;// <-- this cout doesn't print when segfault
        tmp = ostatnioUlozony;
        cout << " debug cout " ; // <-- this cout doesn't print when segfault
        ++tmp; // <-- segfault
    } ...

If the method was call and don't have segfault every cout from T1 and before was printed. In line ++tmp is segfault because ostatnioUlozony is NULL, when method go to T2 every cout without first wasn't printed. Why?

I'm using Netbeans ang gcc, I found the "segfault line" with debug in Netbeans, but before I use then I spend some time on adding cout line and running program.

Thanks a lot,

You need to flush the output stream with either std::flush or std::endl (which will give a newline as well), otherwise you are not guaranteed to see the output:

cout << " second task " << std::flush;

Nonetheless, you have undefined behaviour if you increment a singular iterator (which the null pointer is), so this is only likely to work. As far as C++ is concerned, your program could launch a nuclear missile instead.

Another solution is to use std::cerr instead of std::cout. It is unbuffered, so no flushing is required, and it's slightly more idiomatic to use std::cerr for debugging purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM