Change stack memory from program C

I am new to stackoverflow, so I apologize in advance for any errors that I make.

I ran into 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; } 

Expected Result:

 Hello Hai How are you? 

The task requires changing the output as follows by adding some code to the change () function

 Hello How are you? 

You should not make any changes to main ().

I tried to change the return address of the change () function stored in the stack memory, and there, avoiding the printf ("\ nHai") operator. But I get errors when compiling using gcc.

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

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

Values ​​added to ch (10 and 20) are fixed with

 objdump -d ./a.out 

I hope to get some suggestions to solve the problem. Thank you for your time and patience.

+6
source share
1 answer

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" and then execute the change () function, which will print "How are you?" on a new line, and then exit the program. The exit () function is part of the c standard library, as you can see here.

0
source

All Articles