0

The output of this code is

char *str="char *str=%c%s%c;main(){printf(str,34,str,34);}";main(){printf(str,34,str,34);}

I don't know how this is happening. Please explain.

#include<stdio.h>
char *str = "char *str=%c%s%c;main(){printf(str,34,str,34);}";

int main()
{
        printf(str,34,str,34);

        return 1;
}
3
Contributors
2
Replies
18
Views
4 Years
Discussion Span
Last Post by sepp2k
0

Any time you venture out into the "weeds" of undefined behavior, the results can be odd or just what you might expect.

The point is, why bother? It's an unproductive line of inquiry at best - a complete mockery of the standards of the C language, and your ability to see the wisdom of working within those standards, at worst.

Edited by Adak

0

Which parts are you confused about specifically? The %cs in the format string are used, so that the " characters (ASCII value 34) can be inserted without messing with backslashes. Other than that the main trick is that str is used both as the format string as well as the argument to %s, so that the format string can appear verbatim in the printed output without having to repeat it.

PS: To make this a proper quine you should add the include, the return type of main and the return statemetn to the format string. You'd also need to add additional %cs for the line breaks if you want those to be reproduced as well.

PPS: When the application exits successfully, it should return 0, not 1.

Any time you venture out into the "weeds" of undefined behavior, the results can be odd or just what you might expect.

Where and how does this code invoke undefined behavior? I don't see it.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.