Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self reproducing program

main(a){printf(a="main(a){printf(a=%c%s%c,34,a,34);}",34,a,34);}

How it is reproducing itself after compilation? What is the role of writing 34 in printf function?

like image 985
Anil Arya Avatar asked Dec 21 '11 20:12

Anil Arya


1 Answers

34 is the ASCII character code for a double-quote (") character.


To follow up on my tangential comment (it was a reference to Hofstadter's "Godel Escher Bach"), this works because it's a quine, which is basically a recipe containing two elements: a kernel of data and an operation on that kernel, such that when the operation is complete the original recipe is reproduced. To do this, the kernel and the operation are almost identical. In the program you mention, the kernel is the string

 "main(a){printf(a=%c%s%c,34,a,34);}"

and the operation is the rest of the program:

 main(a){printf(a=_____,34,a,34);}

where ____ is the kernel. You'll note they look essentially the same: the operation can print itself by using the kernel as a format specifier (which prints the kernel but unquoted, thus transforming the kernel into the operation in the output), and also feeding the kernel itself as a parameter in the format specifier (the %s) and quoting it, yielding the kernel in the output.

operation(quoted kernel) => unquoted kernel that includes a copy of the kernel, quoted => which is the original program.


one more point: the reason it uses this 34 business is that it keeps the quoting operation easy by using a kernel without quote characters; if you tried to use

"main(a){printf(a=\"%s\",a);}"

as the kernel, with an unquoted kernel of

main(a){printf(a="%s",a);}

it would be much more difficult because in order to quote the kernel, you'd have to backslash-escape the quotes in the middle of the string.

like image 83
Jason S Avatar answered Sep 22 '22 06:09

Jason S