missing cout before segmentation fault
Asked Answered
S

2

6

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,

Scottscotti answered 7/4, 2013 at 11:54 Comment(2)
You should use a debugger if you want to track the flow of execution in your programOud
I did this, but I want to know why I didn't saw coutScottscotti
C
11

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.

Catchment answered 7/4, 2013 at 11:55 Comment(2)
Thanks :) When I increment iterator I didn't know that it's NULLScottscotti
I learned to use \n to flush the buffer in 1996 on SunOS and have used it since. I guess some things change.Hyperbola
F
2

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.

Formication answered 8/4, 2013 at 10:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.