Reputation: 77
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.
Upvotes: 6
Views: 1210
Reputation:
You were close. The following is on linux on x86-64.
main.c:
#include <stdio.h>
void change()
{
char dummy;
/* skip local variable and rbp */
*(long*)(&dummy + sizeof(dummy) + sizeof(long*)) += 0x40055e - 0x400554;
}
int main()
{
printf("Hello\n");
change();
printf("Hi\n");
printf("How are you?\n");
return 0;
}
output:
$ gcc -fno-stack-protector -o main main.c
$ ./main
Hello
How are you?
from objdump we get:
40054f: e8 c8 ff ff ff callq 40051c <change>
-> 400554: bf 1a 06 40 00 mov $0x40061a,%edi
400559: e8 92 fe ff ff callq 4003f0 <puts@plt>
-> 40055e: bf 1e 06 40 00 mov $0x40061e,%edi
400563: e8 88 fe ff ff callq 4003f0 <puts@plt>
Process:
First use a small arbitrary difference in main.c
. Then compile and run objdump -d main
to get the actual offsets and update main.c
with their difference.
Upvotes: 3
Reputation: 1271
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
Upvotes: 2