Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this obfuscated C example do?

Tags:

c

I read this hoax: https://www.gnu.org/fun/jokes/unix-hoax.html

And it contains some obfuscated C code which is:

for(;P("\n"),R--;P("|"))for(e=C;e--;P("_"+(*u++/8)%2))P("| "+(*u/4)%2);

I added the minimum code to make it work, and it ended this way:

#include <stdio.h>

#define P(...)  printf(__VA_ARGS__)
#define C   (7)


int main(int argc, char *argv[])
{
    auto    R;
    auto    e;
    auto    *u;

    R   = 5;

    for(;P("\n"),R--;P("|"))for(e=C;e--;P("_"+(*u++/8)%2))P("| "+(*u/4)%2);
}

After compiling and checking that it works (and prints something), I wrote the code with some less obfuscation:

#include <stdio.h>

#define C   (7)

int main(int argc, char *argv[])
{
    auto    R;
    auto    e;
    auto    *u;

    R   = 5;


    while(R) {
        /* for1: param 2.1 */
        printf("\n");
        /* for1: param 2.2 */
        R--;

        for(e = C; e; ) {
            /* for2: param 2 */
            e--;

            printf("| " + (*u / 4) % 2);

            /* for2: param 3 */
            printf("_" + (*u++ / 8) % 2);
        }

        /* for1: param 3 */
        printf("|");

    }
    /* for1: param 2.1 */
    printf("\n");
}

After compiling like this: $ gcc tst.c -o tst I see two different outputs (Undefined behaviour I suppose):

$ ./tst 

| _| _ _ | _| _ |
 |    | _ |
 _  _ | _ | _|
  _ | _   |
 _ |  | _ | |
$ ./tst 

| _| _|  | _| __|
 |  | _ | _ |
|  |   | _|
   | _ |
|  _  _|

So now to the point: What the hell does this do?

printf("| " + (*u / 4) % 2)

or even worse:

printf("_" + (*u++ / 8) % 2)
like image 868
alx Avatar asked Feb 23 '26 14:02

alx


1 Answers

u is not initialized in the original code or your additions. Presuming it had a proper value, then, if *u is not negative:

"| " + (*u / 4) % 2

is a pointer to the character '|' or ' ' according to whether *u is 0-3 or 4-7 modulo 8. In effect, printf is passed either "| " or " ". Thus, the printf will print either “| ” or “ ”.

And:

"_" + (*u++ / 8) % 2

is a pointer to either the '_' or the null character that terminates the string according to whether *u is 0-7 or 8-15 modulo 8, before the increment. Thus, the printf will print either “_” or nothing.

like image 175
Eric Postpischil Avatar answered Feb 26 '26 04:02

Eric Postpischil