xorl %eax, %eax

C Quiz No. 2

with one comment

Continuing from the first one back in 2009, here is another that a friend of mine send me yesterday.

The concept is that you are free to put whatever you want in do_your_stuff() in order to make it print “win” from function do_my_stuff().

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

void 
do_your_stuff(void)
{
	// do whatever you want
}

void 
do_my_stuff(void)
{
	char c[100];
	unsigned int i, r_index;

	srand(time(NULL));
	for(i = 0; i<1000; i++)
		r_index = rand() % (sizeof(c) - 1);

	printf("c[%u] = %02x\n", r_index, c[r_index]);

	if (c[r_index] == 0x20)
		printf("win!\n");
	else
		printf("fail\n");
	
	return;
}

int 
main(void)
{
	do_your_stuff();
	do_my_stuff();
	return 0;
}

Instantly I came up with a quite simple solution that exploits the concept of uninitialized stack that it’s being used.

void 
do_your_stuff(void)
{
	char buf[2048]; int i;
	for(i=0; i<sizeof(buf); i++) buf[i] = 0x20;
}

Which it works…

$ ./cquiz2
c[98] = 00
fail
$ ./cquiz2
c[81] = 7f
fail
$ gcc -Wall -Werror --std=c99 cquiz2.c -o cquiz_sol
$ ./cquiz_sol
c[43] = 20
win!
$ ./cquiz_sol
c[54] = 20
win!
$

I found it fun so if you have any other solutions feel free to comment on this post.

Written by xorl

May 18, 2013 at 16:44

Posted in C programming, fun

One Response

Subscribe to comments with RSS.

  1. How about:

    void
    do_your_stuff(void)
    {
    // do whatever you want
    #define if printf(“win\n”); if
    }

    Sharkey

    May 18, 2013 at 16:53


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s