Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the Stack Memory from C program

Tags:

c

I am new to stackoverflow, so I apologize in advance for any mistakes I commit.

I have come across this C puzzle Recently. The program is given below.

#include<stdio.h>

void change()
{

}

int main()
{
 printf("\nHello");
 change();
 printf("\nHai");
 printf("\nHow are you?");
 return 0;
}

The expected output is,

Hello
Hai
How are you?

The problem asks us to change the output as follows by adding some code in function change()

Hello
How are you?

You are not supposed to make any changes in the main().

I tried to change the return address of the function change() stored in the stack memory and there by avoiding the statement printf("\nHai"). But I am getting errors when I compiled using gcc.

The code I added in change() is shown below.

void change()
{
 char ch;
 *(&ch+10)+=20;
} 

The values added to ch (10 and 20) are fixed by using

objdump -d ./a.out

I hope to receive some suggestions to solve the problem. Thanking you in advance for your time and patience.

like image 518
Emil Tom Avatar asked Mar 11 '13 16:03

Emil Tom


1 Answers

The following code should achieve the desired effect.

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

void change()
{
printf("\nHow are you?"); 
exit(0);
}

int main()
{
 printf("\nHello");
 change();
 printf("\nHai");
 printf("\nHow are you?");
 return 0;
}

This code will cause the program to print "Hello" then execute the change() function which will print "How are you?" on a newline and then exit the program. The exit() function is part of the c standard library as can be seen Here

like image 158
Ace.C Avatar answered Sep 28 '22 06:09

Ace.C