strange output in c program
Mateusz Guzik
mjguzik at gmail.com
Wed Jul 8 12:59:31 UTC 2020
On 7/8/20, rahul deshmukh <rahul.dshmkh1 at gmail.com> wrote:
> Hi Team,
> i was learning c programming and came across a very strange output. kindly
> someone please guide me if i am missing anything.
>
> rdx at FreeBSD:~/Projects/Clang/chapter3 % uname -a
> FreeBSD FreeBSD 12.1-RELEASE FreeBSD 12.1-RELEASE r354233 GENERIC amd64
> ========================================================================
> rdx at FreeBSD:~/Projects/Clang/chapter3 % cat example6.c
> #include <stdio.h>
> int main()
> {
> int a = 300, b, c;
> if(a >= 400)
> {
> printf("shouldn't print\n");
> b = 300;
> }
> c=200;
> printf("%d %d\n", b, c);
> return 0;
> }
> =========================================================
> rdx at FreeBSD:~/Projects/Clang/chapter3 % make example6
> `example6' is up to date.
> rdx at FreeBSD:~/Projects/Clang/chapter3 % ./example6
> 300 200==> should be garbage value instead of 300?
>
300 is perfectly fine garbage. You are tricking yourself a little bit
here by expecting something glaringly obvious.
Take a look at this (ran on fresh development version, FreeBSD clang
version 10.0.1 (git at github.com:llvm/llvm-project.git
llvmorg-10.0.1-rc1-0-gf79cd71e145):
$ cc -O2 test.c
$ ./a.out
300 200
$ cc -O0 test.c
$ ./a.out
32767 200
Same source code, different compilation flags resulting in different assembly.
Correct enough and useful way to look at it is: since b is not
initialized, the behavior is undefined. This means literally anything
can happen. In practice for code like this the compiler will tend to
generate the call to printf, but some values which will get passed
down will be (a possibly) unintentional side effect of assembly which
precedes said call. The function will read the stack and/or various
registers and *something* is always there. If the source code is
correct, it is the intended stuff. If the source is not correct (like
in your testcase), it can be just about anything including leftovers
from previous calls.
So no, a buggy program is not guaranteed to print something which looks wrong.
--
Mateusz Guzik <mjguzik gmail.com>
More information about the freebsd-hackers
mailing list