Search code examples
cdebuggingsegmentation-faultprintf-debugging

C Programming: seg faults, printf, and related quirks


As many young programmers do, I learned the usefulness of inserting numerous print-to-console statements of "here1," "here2," and so on at different points in code to figure out when my programs are going awry. This brute force debugging technique has saved me many, many times throughout my CS studies. However, when I started programming in C, I stumbled onto an interesting problem. If I were to try and run

void* test;

printf("hello world");
test[5] = 234;

Of course I get a segfault for not malloc'ing memory for testChar. However, you would think logically that "hello world" would be printed before the seg fault happens, since that is the flow of the code, but in my experience, it is always the case that the seg fault happens first, and "hello world" is never printed to the console at all. (I wasn't able to test this exact example, but I have run into this sort of situation many times using gcc on a linux box.) I'm guessing this has to do with either the compiler rearranging some things and/or printf using some sort of buffer that is flushed asynchronously and therefore not being immediate. This is entirely speculation on my part because I honestly don't know why it happens. In any other language that I have used, no matter what problem the "testChar =..." line caused, the "hello world" would still be printed, and thus I could determine where the problem is.

My question is why does this happen when I'm programming C? Why isn't the hello world printed first? And secondly, is there a better C programming debugging technique than this that accomplishes the same basic thing? As in, an easy/intuitive way to find the line of code that is a problem?

Edit: I gave a working example by accident haha. What I have now should cause a segfault. It's funny how usually when I don't want a segfault I get one, and now when I actually wanted one I wrote legal code!


Solution

  • The code you posted is perfectly legal and should not cause a segfault - there is no need to malloc anything. Your problem must lie somewhere else - please post the smallest example of code that causes the problem.

    Edit: You have now edited the code to have a totally different meaning. Still, the reason that "hello world" is not displayed is that the the output buffer has not been flushed. Try addinig

    fflush( stdout );
    

    after the printf.

    Regarding locating the source of the problem you have a couple of choices:

    • liberally sprinkle printfs through your code using the __FILE__ and __LINE__ C macros
    • learn to use your debugger - if your platform supports core dumps, you can use the core image to find where the error is.