sth about excutable string?

#include <stdio.h>
int main(int a)
{
char* x = "bB_Z#^B_Z#h1AI.BMB5#VB2>2:B>>=6#RB@1.>>L12#NB6N:>BN#JFHL1@D6#";
while(a = *x / 4) a -= 8, printf("\n%*s" + !!a, a, "_/_/_/" + *x++ % 4 * 2);
getchar();
return 0;
}

OK,It's really a funny program,but why? Why no errs? How does it work?
Who can explain?
Thanks.
The string is not executable. The program uses the ASCII value of each character in the following way.

First note that x is incremented by one every printf(), and we only ever look at the character pointed to by x. Which means that we look at each character in the string.

a = *x / 4. So a is given the value of the ASCII value of the character divided by 4. The loop ends when *x/4 == 0, which is only the case when *x < 4. Since the string is NULL terminated, the NULL character at the end stops the loop.

Note the comma operator a -= 8, ...

Comma is just a way to do two things on one line of code. Replace the comma with a semicolon and add braces around the two lines of the while loop and the program is unchanged.

First subtract 8 from a.

printf( "\n%*s" + !!a )

Neat. !!a is a programming trick used to convert any nonzero value to 1 and zero to zero. "\n%*s" is a character pointer. One can add to pointers; if a is now 1, adding 1 to the character pointer yields "%*s" -- a nice way to not print out the \n every time.

The same trick is used on the last part of the printf:

printf( "_/_/_/" + *x++ % 4 * 2 );

Again, we add either 0, 2, 4, or 6 to the char* string to either print out one set of _/, two, three, or no sets. (Note the * 2 is there because _/ is 2 characters).

EDIT:

The one other detail I omitted was use of the %*s in the format string.
%10s, for example, says to use a field width of 10 to print the string.
%*s says to use the next argument as the field width. The code passes
in a. This is how the program manages to print blanks.

Very nice obfuscated program. The char* string encodes three pieces of information in each byte: 1) whether or not to print a newline; 2) the field width; 3) the number of _/ to print.

Last edited on
This does the same thing (not very cleanly):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>

using namespace std;

int main()
{
    char* x = "bB_Z#^B_Z#h1AI.BMB5#VB2>2:B>>=6#RB@1.>>L12#NB6N:>BN#JFHL1@D6#";
    for( int a; a = *x / 4; ++x ) {
        a -= 8;
        if( a == 0 )
            cout << endl;
        else if( a > 0 )
        {
            int numChars = 6 - 2 * ( *x % 4 );
            int numSpaces = a - numChars;

            if( numSpaces > 0 )
                cout << string( numSpaces, ' ' );
            for( ; numChars > 0; numChars -= 2 ) 
                 cout << "_/";
        }
    }
}

Last edited on
Got it .
Thank u so much~
Topic archived. No new replies allowed.