C Code: How does these even work?

后端 未结 4 1927
既然无缘
既然无缘 2021-02-04 01:02

I just saw this here

#include 

int main(int argc, char *argv[printf(\"Hello, world!\\n\")]) {}

What this does is print \"Hello

4条回答
  •  难免孤独
    2021-02-04 02:04

    If I figure out how the compiler parsed it, I'll update this, but at least there needs to be no guesswork as to how it compiled:

    
    objdump --disassemble /tmp/hello (edited):
    
    080483c4 
    : 80483c4: 55 push %ebp 80483c5: 89 e5 mov %esp,%ebp 80483c7: 83 e4 f0 and $0xfffffff0,%esp 80483ca: 83 ec 10 sub $0x10,%esp 80483cd: b8 a0 84 04 08 mov $0x80484a0,%eax 80483d2: 89 04 24 mov %eax,(%esp) 80483d5: e8 22 ff ff ff call 80482fc 80483da: c9 leave 80483db: c3 ret 80483dc: 90 nop 80483dd: 90 nop 80483de: 90 nop 80483df: 90 nop

    Since Linux executables are based normally at 0x8048000, the address of the argument to printf is at an offset of 0x00004a0 from the start of the binary:

    
    xxd /tmp/hello | grep 00004a0
    
    00004a0: 4865 6c6c 6f2c 2077 6f72 6c64 210a 0000  Hello, world!...
    

    So, the address of the string is pushed, and printf is called with that one arg. Nothing magical at that level, so all the fun stuff was done by gcc.

提交回复
热议问题