By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,991 Members | 1,887 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,991 IT Pros & Developers. It's quick & easy.

a c++ puzzle

P: 2
void change()
{
int buf[1]={0};
buf[2]+=7;
}
void main()
{
int i=10;
change();
i=555;
printf("The value of i is %d",i);
}

The output of the above program is 10 instead of 555.how is tht possible. i tried debugging it , and its not executing the i=555 statement at all. Could anyone help me out here???
Jun 19 '07 #1
Share this Question
Share on Google+
4 Replies


P: 15
:)) You simply increase returned address on change() stack frame. That's why you jump over i=555; statement on the main function.



void change()
{
int buf[1]={0};
buf[2]+=7;
}
void main()
{
int i=10;
change();
i=555;
printf("The value of i is %d",i);
}

The output of the above program is 10 instead of 555.how is tht possible. i tried debugging it , and its not executing the i=555 statement at all. Could anyone help me out here???
Jun 19 '07 #2

P: 2
Thanx but cud u also explain the two statements in the change() function.
Jun 19 '07 #3

Expert 100+
P: 181
:)) You simply increase returned address on change() stack frame. That's why you jump over i=555; statement on the main function.
can u be more clear plemoine, how he is able to change the return address of change. as per my understanding retrun address are pushed into stack. is the code
buf[2] += 7; modifying stack
Jun 19 '07 #4

Expert 10K+
P: 11,448
The OP must be a very lucky man; accessing an element beyond an array causes
undefined behaviour; i.e. anything could have happened (daemons that fly out
of your nose or worse). Every answer at *what* actually happened is as good
as another: the behaviour is undefined (as defined per the Standard).

kind regards,

Jos
Jun 19 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.