strange output in c program
Paul FLOYD
pjfloyd at wanadoo.fr
Wed Jul 8 14:25:46 UTC 2020
As already said, when you have UB anything can happen.
First recommendation. Listen to your compiler!
paulf> clang -Weverything -g -o test2 test2.c
test2.c:5:7: warning: variable 'b' is used uninitialized whenever 'if' condition
is false [-Wsometimes-uninitialized]
if(a >= 400)
^~~~~~~~
test2.c:11:22: note: uninitialized use occurs here
printf("%d %d\n", b, c);
^
test2.c:5:4: note: remove the 'if' if its condition is always true
if(a >= 400)
^~~~~~~~~~~~
test2.c:4:18: note: initialize the variable 'b' to silence this warning
int a = 300, b, c;
^
= 0
clang is even telling you how to fix your errors.
Even if the compiler can't pick up the error, you can also test at runtime:
==55524== Memcheck, a memory error detector
==55524== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==55524== Using Valgrind-3.17.0.GIT and LibVEX; rerun with -h for copyright info
==55524== Command: ./test2
==55524==
==55524== Conditional jump or move depends on uninitialised value(s)
==55524== at 0x49B2E65: ??? (in /lib/libc.so.7)
==55524== by 0x49AF184: vfprintf_l (in /lib/libc.so.7)
==55524== by 0x49FB203: printf (in /lib/libc.so.7)
==55524== by 0x20133B: main (test2.c:11)
A+
Paul
More information about the freebsd-hackers
mailing list