Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the 1987 Korn oneliner print unix? [closed]

OK, I will bite. An answer to the massively popular Why does the C preprocessor interpret the word "linux" as the constant "1"? question mentions that

main() { printf(&unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);}`

prints "unix", but for reasons that have absolutely nothing to do with the spelling of the macro name.

I read http://www.ioccc.org/1987/korn.hint but I think quite more detail would help unobfuscating this :)

like image 387
chx Avatar asked Oct 10 '13 14:10

chx


1 Answers

unix is 1 because of an implicit #define in the compiler or the runtime environment.

Thus, and because a[b] == b[a] == *(a + b) and thus 1["xy"] == "xy"[1], you get:

  • &unix["\021%six\012\0"] points to "%six\012\0"
  • (unix)["have"] = "have"[1] = 'a',
  • "'a'+"fun"-0x60" = "fun" + 1 = "un".

This leads you to printf("%six\012\0", "un"); which clearly does print "unix\012", \012 being a line break (the same as \n).

If unix is undefined, e. g. on a Windows system, you get an error.

If unix was 0 (can that ever be the way on a clean system?), you get

printf("\012%six\n", 'h'+"fun"-0x60)

where the 2nd argument is "fun"+8, pointing to Nirvana and leading to undefined behaviour.

like image 91
glglgl Avatar answered Oct 12 '22 03:10

glglgl