kernelthread.com

Reflect

Introduction

This program upon being run outputs the reverse of itself, syntactically speaking, that is. Thus, the output is a character by character reverse of the original code (it is assumed that there are no trailing new-lines in the original code, and no trailing new-line is thus output. This means that when this program is run from the command line of a Unix shell, say, you would have to append an echo to actually see the output:

% ./reflect; echo

Furthermore, you cannot really beautify the code or reformat it in any way, since changing even a single character would render it incorrect and useless (sure, as if it is blindingly useful otherwise).

In my opinion, the code is a horrible candidate for being a first example of using malloc. It is also an example of a situation where indentation or beautification of the code renders it incorrect, correctness being a visual requirement here. The cb guys, the indent guys and others related may wish to appropriately modify their packages for handling such cases - meaning a code reformatting program would need to modify the code along with the layout in order to preserve the desired semantics.

It may also be worthwhile to note that this is a one-liner, with magic numbers all over the place. Although self-mirroring code is interesting, it would be more fun to have the code mirror at variable angles specified at run-time.

Source

main(){int i;char *k;char a[]="main(){int i;char *k;char a[]=%c%s%c;\ k=(char *)malloc(220);for(i=0;i<219;i++){k[i]=a[218-i];}*(k+219)=0;\ strcpy(a,k);a[183]=k[184];a[184]=k[183];a[185]=k[184];a[186]=k[185];\ a[187]=k[184];a[188]=k[187];printf(a,34,k,34);}";k=(char*)malloc(220);\ for(i=0;i<219;i++){k[i]=a[218-i];}*(k+219)=0;strcpy(a,k);a[183]=k[184];\ a[184]=k[183];a[185]=k[184];a[186]=k[185];a[187]=k[184];a[188]=k[187];\ printf(a,34,k,34);}

Download

reflect.c