简体   繁体   中英

Why printf doesnt work when *(int *)(0) = 0; exists

I have following code:

main ()
{
    printf("Hello world !");
    *(int *)(0) = 0;
}

When I compiled this code and ran, it didn't print the string to console. After that, I modified a little:

main ()
{
    printf("Hello world !\n");
    *(int *)(0) = 0;
}

And, it worked !

I think the mystery behind is *(int *)(0) = 0; but don't know why !

Ps. I'm using gcc 4.8.2 to compile.

The immediate reason is that FILE * operations are buffered, and stdout in particular is usually line-buffered (when it's interactive, at least). If no \\n is seen and fflush is not called explicitly before the crash, nothing will actually be written to the underlying file descriptor.

The greater problem is that dereferencing a NULL pointer is UNDEFINED BEHAVIOR . There are absolutely no constraints on what might happen. If the compiler can prove that printf will always return, then the UB is allowed to propagate to before the call, making the entirety of main UB. That said, it is quite difficult for the compiler to prove this, and in particular since FILE usually involves a vtable it's not actually true. But the point is that you can't even trust UB to wait until a particular time.

fflush(stdout) 紧跟在您的 printf 之后,您将看到崩溃前的字符串。

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