Hi,
when i tried to run compile and execute this statement in a simple c file:
main(){ printf("%d");}
on HP it's is giving me 64 and on AIX its giving me 804359524.
Could anyone tell me what is this behavior.
Hi,
when i tried to run compile and execute this statement in a simple c file:
main(){ printf("%d");}
on HP it's is giving me 64 and on AIX its giving me 804359524.
Could anyone tell me what is this behavior.
The code is exposing Undefined Behavior. On other systems it might print "Stack Overflow", (seriously!). %d tells the CRT library that you'll provide an integer, but you don't.
I assume you mean:
int main()
{
printf("%d");
}
That being the case, printf() is reading an int (as directed by the format specifier %d) from the stack. Since you've not specified one, it's just reading whatever is on the stack and using that. Hence, your seeing pseudo-random output.
Instead, try:
int main()
{
printf("%d", 10101);
}
HTH
My guess is that you compile
main(){ printf("%d");}
This will pick a random value off the current stack. Try this:
main() {
printf("%d", 0);
printf("%d");
}
Now, the second printf()
will always print 0
since it gets the same stack as the first call.
[EDIT] This doesn't work on x86 Linux with GCC 4.1.2. Here is the generated assembler code (use gcc -S -o t.s t.c
):
movl $0, %esi
movl $.LC0, %edi
movl $0, %eax
call printf
movl $.LC0, %edi
movl $0, %eax
call printf
As you can see, the second argument isn't pushed on the stack but passed via %esi
(which is a register). That same register is probably modified in printf()
which is why it's losing its value. Damn optimizations ;)
This is classic undefined behavior. The compiler doesn't check that you provide enough arguments to match your formatting string. There are compilers that do this (gcc is one), but yours doesn't.
The code in printf()
will happily step through its given formatting string, and when it gets to the "%d" it will read off one int
-sized argument (typically: from the stack), not knowing there is no argument there for it to read.
Whatever value happens to be on the stack gets printed.
Some compilers, like gcc, will catch this type of oh so common problems if you specify a high enough warning level. Like this (compiling you code, with -Wall - all warnings) :
gcc -c -g -Wall -MMD -MP -MF build/Debug/Cygwin-Windows/newmain.o.d -o build/Debug/Cygwin-Windows/newmain.o newmain.c
newmain.c: In function `main':
newmain.c:16: warning: too few arguments for format
This is one of around 998 good reasons to always compile with a high warning level, and to take the warning messages seriously.