Click to See Complete Forum and Search --> : Can u give the Solution


SandyG
September 29th, 2005, 09:52 AM
Hello Gurus,

Can u give any solution for the below code.


Thanks
Sandy




void change()
{
//Do any thing that will print value of i in main as 5;
//without changing code of main
}

int main()
{
int i = 5 ;

clrscr();

change();

i = 10;

printf("Value of i=%d",i);

getch();

return 1;
}

TheMachineElf
September 29th, 2005, 10:40 AM
void change()
{
int x = 0;

printf("Value of i=%x\n",*((&x) + 22));
}Visual C++ 6.0, standard Debug console settings.

Not portable, not useful.


Pete

Smasher/Devourer
September 29th, 2005, 03:37 PM
TheMachineElf: That does cause i=5 to be printed in the function change(), but i is still set to 10 and that value is printed when execution returns to main(). I think the point of the question was to write change() in such a way so that i=5 is printed from the existing printf() statement in main(). SandyG, I doubt that there is any graceful, portable way to do this, and I can't imagine why you'd want one, but here's a terrible hack that does the job, at least in VC++ 6.0 with the Debug settings.
void change()
{
__asm
{
mov eax,dword ptr [ebp+4]
add eax,7
mov dword ptr [ebp+4],eax
}
}
It loads the return address that was stored during the call to change() and alters it so that once change() is finished, execution returns to the line after the assignment i = 10, so that line is never executed. Again, this is a terrible hack and will break if you even look at it the wrong way. It's good for nothing except as a curiosity. I can't think of any reliable way to do what you want.

RoboTact
September 29th, 2005, 04:25 PM
maybe somehow cheat stdout to catch printed string and replace it with required?

wschweit
September 29th, 2005, 05:08 PM
This works on VC++ 7.1. Main still doesn't print out 5, but it doesn't print out 10.


void change()
{
printf("Value of i=%d",5);
stdout->_file = NULL;
}


Could also do this, but I guess technically it does change the code in main...


void change()
{
#define printf(x,y) printf(x,y/2)
}