S
sukrit.mehra
Hi People,
Few of my colleuages were flexing their C muscles and they asked me
this question.
void Function(void);
int main(void)
{
int x=5;
Function();
x=10;
printf("%d", x);
return 0;
}
What would be the defination of Function such that printf prints 5
instead of 10?
Possibilities:
1. Write a macro to replace defination of printf. Not a neat solution,
so ignore!
2. The whole code would be loaded in the RAM somewhere, so all we have
to do is change the line x = 10 to x = 5 in the code section. So we
need address of that paritcular instruction. Can such a thing be done?
Also, are Code Sections usuaully RO? Is it architecture specific?
Compiler/LInker Specific?
3. This is the best solution, it's code is given below. Basically i
still don't fully understand it and the person who gave this to me,
doesn't want me to understand
void Function(void)
{
int i;
int *j=&i;//J points to i
*(j+2)+=7;//increment the value(return address) at j+2th loc by 7
//How do we know j+2 is the return address
//Why increment by 7?
//Basically what are the magic numbers?
}
What I can figure out is that they are playing with the return address
of the function and changing it to point to some other instruction. But
how? What is the strucutre of C's function stack? Where is the return
address stored? Is it complier specific? If yes, how to find such
details?
Thanks for your time!
Regards
Sukrit
Few of my colleuages were flexing their C muscles and they asked me
this question.
void Function(void);
int main(void)
{
int x=5;
Function();
x=10;
printf("%d", x);
return 0;
}
What would be the defination of Function such that printf prints 5
instead of 10?
Possibilities:
1. Write a macro to replace defination of printf. Not a neat solution,
so ignore!
2. The whole code would be loaded in the RAM somewhere, so all we have
to do is change the line x = 10 to x = 5 in the code section. So we
need address of that paritcular instruction. Can such a thing be done?
Also, are Code Sections usuaully RO? Is it architecture specific?
Compiler/LInker Specific?
3. This is the best solution, it's code is given below. Basically i
still don't fully understand it and the person who gave this to me,
doesn't want me to understand
void Function(void)
{
int i;
int *j=&i;//J points to i
*(j+2)+=7;//increment the value(return address) at j+2th loc by 7
//How do we know j+2 is the return address
//Why increment by 7?
//Basically what are the magic numbers?
}
What I can figure out is that they are playing with the return address
of the function and changing it to point to some other instruction. But
how? What is the strucutre of C's function stack? Where is the return
address stored? Is it complier specific? If yes, how to find such
details?
Thanks for your time!
Regards
Sukrit