Is it safe to disable buffering with stdout and stderr?

前端 未结 5 459
我寻月下人不归
我寻月下人不归 2021-02-03 11:01

Sometimes we put some debug prints in our code this way

printf(\"successfully reached at debug-point 1\\n\"); 

some code is here

printf(\"successfully reached          


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-03 11:38

    It is "safe" in one sense, and unsafe in another. It is unsafe to add debug printfs, and for the same reason unsafe to add code to modify the stdio buffering, in the sense that it is a maintenance nightmare. What you are doing is NOT a good debugging technique. If your program gets a segfault, you should simply examine the core dump to see what happened. If that is not adequate, run the program in a debugger and step through it to follow the action. This sounds difficult, but it's really very simple and is an important skill to have. Here's a sample:

    $ gcc -o segfault -g segfault.c   # compile with -g to get debugging symbols
    $ ulimit -c unlimited             # allow core dumps to be written
    $ ./segfault                      # run the program
    Segmentation fault (core dumped)
    $ gdb -q segfault /cores/core.3632  # On linux, the core dump will exist in
                                        # whatever directory was current for the
                                        # process at the time it crashed.  Usually
                                        # this is the directory from which you ran
                                        # the program.
    Reading symbols for shared libraries .. done
    Reading symbols for shared libraries . done
    Reading symbols for shared libraries .. done
    #0  0x0000000100000f3c in main () at segfault.c:5
    5               return *x;          <--- Oh, my, the segfault occured at line 5
    (gdb) print x                       <--- And it's because the program dereferenced
    $1 = (int *) 0x0                     ... a NULL pointer.
    

提交回复
热议问题