Home > Software engineering >  Segmentation fault prevents prior printf
Segmentation fault prevents prior printf

Time:11-28

I have already solved the Segmentation Fault, which caused this problem, but I'd still like to know why this was happening:

I have a method which causes a segmentation fault later on in the code, but the printf statment, which is BEFORE the problematic code never gets excecuted.

element* insert_sorted(element *first, element *new_elem)
{
    printf("%lld", new_elem->isbn); 

    
    // Some funny code which causes a Segmentation Fault
}
// Output: Segmentation Fault only, not even the expected first ISBN

But if I return before this code, it prints just fine

element* insert_sorted(element *first, element *new_elem)
{
    printf("%lld", new_elem->isbn);

    return NULL;
    // Some funny code which causes a Segmentation Fault
}
// Output: Prints all the ISBN numbers just fine

And lastly, if I put a line break into the print, it prints the first two ISBNs and than it gives an Segmentation Fault.

element* insert_sorted(element *first, element *new_elem)
{
    printf("%lld\n", new_elem->isbn);


    // Some funny code which causes a Segmentation Fault
}
// Output: First two ISBNs and than a Segmentation Fault

Question 1:

How is it possible that a Segmentation Fault prevents printing text to the console? Is the order of execution broken??

Question 2:

How is it possible, that adding a character (\n) changes this behaviour? And why would it still only print the first two times? (This function gets called about 20 times.)

Question 3:

How can I debug my code, when errors are 'eating' my debugging information? :(

(The code is part of a homework, so I can't post the entire code.)

CodePudding user response:

How is it possible that a Segmentation Fault prevents printing text to the console?

The program most probably has undefined behavior and anything could happen. In this case, if you print (without \n) the text most probably stays in the output buffer and is discarded when the program crashes. If you want to print what's in the buffer without a \n, add fflush(stdout);.

How is it possible, that adding a character (\n) changes this behaviour?

\n makes it print what's stored in the output buffer.

And why would it still only print the first two times? (This function gets called about 20 times.)

Again, the program probably has undefined behavior and it could do just about anything - at any time.

How can I debug my code, when errors are 'eating' my debugging information?

The easiest way would be to start the debugger and step through the code line by line. If you are using gcc or clang you can also get very useful information about where the problem is by compiling with

-g -fsanitize=address,undefined

and rerun the program. That usually give valuable hints.

  • Related