Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Varying C code output

Tags:

c

I tried the code in my system. This is what I got...... 1)

    #include <stdio.h>

    int main()
    {
        //int a = 10;
        printf("%s");
        return 0;
    }

Output:
1í^áäðPTRhh

2)

    #include <stdio.h>

    int main()
    {
        int a = 10;
        printf("%s\n");
        return 0;
    }

Output:
__libc_start_main

I tried in another system( diff compiler). And the output was different. Actually it must be printing the topmost value in the stack. Then y isn't unique everywhere?

like image 440
aTJ Avatar asked Jan 12 '11 08:01

aTJ


3 Answers

You're dealing with undefined behavior, so you can't expect it to be consistent, nor follow any kind of pattern across compilers, architectures or even runs of the same program.

like image 160
Sebastian Paaske Tørholm Avatar answered Oct 28 '22 21:10

Sebastian Paaske Tørholm


In your printf statement you specified a format specifier %s, which means to print a string. It will check the top of the stack and print the string present on top of stack

Stack arrangement is completely Compiler dependent

The __libc_start_main() function shall perform any necessary initialization of the execution environment, call the main function with appropriate arguments, and handle the return from main() and that was on the top of stack. And that is what you got as output

like image 33
Abi Avatar answered Oct 28 '22 19:10

Abi


Because compilers are free to arrange the contents of the stack however they like. Also, whatever happens to be "at the top of the stack" will be interpreted by printf() as a pointer; there could be any random junk at the corresponding storage location.

like image 28
Oliver Charlesworth Avatar answered Oct 28 '22 20:10

Oliver Charlesworth