Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 8 Jul 2020 14:59:27 +0200
From:      Mateusz Guzik <mjguzik@gmail.com>
To:        rahul deshmukh <rahul.dshmkh1@gmail.com>
Cc:        freebsd-hackers@freebsd.org
Subject:   Re: strange output in c program
Message-ID:  <CAGudoHH-iR9tjGdTYVCu=AaNfzv8P%2BDzNy_RhF6b1Fk%2B_iY_TA@mail.gmail.com>
In-Reply-To: <CAFa7P3fnvqCWfPJU-moJEyx0Wx=bL0sRjhMKLkyiBvN9k6ReSg@mail.gmail.com>
References:  <CAFa7P3fnvqCWfPJU-moJEyx0Wx=bL0sRjhMKLkyiBvN9k6ReSg@mail.gmail.com>

next in thread | previous in thread | raw e-mail | index | archive | help
On 7/8/20, rahul deshmukh <rahul.dshmkh1@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@FreeBSD:~/Projects/Clang/chapter3 % uname -a
> FreeBSD FreeBSD 12.1-RELEASE FreeBSD 12.1-RELEASE r354233 GENERIC  amd64
> ========================================================================
> rdx@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@FreeBSD:~/Projects/Clang/chapter3 % make example6
> `example6' is up to date.
> rdx@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@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>



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?CAGudoHH-iR9tjGdTYVCu=AaNfzv8P%2BDzNy_RhF6b1Fk%2B_iY_TA>