|
-
September 29th, 2005, 09:52 AM
#1
Can u give the Solution
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;
}
-
September 29th, 2005, 10:40 AM
#2
Re: Can u give the Solution
Code:
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
-
September 29th, 2005, 03:37 PM
#3
Re: Can u give the Solution
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.
Code:
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.
-
September 29th, 2005, 04:25 PM
#4
Re: Can u give the Solution
maybe somehow cheat stdout to catch printed string and replace it with required?
"Programs must be written for people to read, and only incidentally for machines to execute."
-
September 29th, 2005, 05:08 PM
#5
Re: Can u give the Solution
This works on VC++ 7.1. Main still doesn't print out 5, but it doesn't print out 10.
Code:
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...
Code:
void change()
{
#define printf(x,y) printf(x,y/2)
}
Last edited by wschweit; September 29th, 2005 at 05:36 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|