Tuesday 26 March 2013

C/C++ Puzzles: PART - 29

Accessing the Stack Memory from C Program

  Recently I have seen this puzzle in which you have access the stack memory from the C Program to obtain a solution. Consider the code given below.

#include <stdio.h>

void change( )
{
        
}

int main( )
{
        printf("Hello\n");
        change( );
        printf("Hai\n");
        printf("How are you?\n");
        return 0;
}

The expected output of the program is shown below

The problem asks us to change the Output to the following form by adding code in the function change( ) alone. You are not supposed to make any change in the main( ) or any other part of the Program.


One simple yet ingenious solution was to add the following code in change( ).


void change( )
{
        printf("Hai\n");
        exit(0);
}


  But the expected solution for this puzzle is obtained by changing the return address of change( ) stored in Stack Memory. There are no functions in C which allows you to do this by directly accessing the stack memory. But the following code can achieve this by finding the location of stack memory from the address of  the variable x declared inside change( ). The code is shown below and the output obtained for this program is the required one.

#include <stdio.h>

void change( )
{
        char x;
        /* skip local variable by changing the return address in the Stack Memory*/
       *(long*)(&x + sizeof(char) + sizeof(long*)) += 10;

int main( )

{

        printf("Hello\n");
        change( );
        printf("Hai\n");
        printf("How are you?\n");
        return 0;

}


Click here to download the C Program.


WARNING!!!
Some Operating Systems might give you segmentation fault on this C Program.

No comments:

Post a Comment