Reputation: 15
I'm running these code
#include <stdio.h>
void Crash(char * cData){
cData[2] = 100;
}
int main() {
char cData[2] = {1,2};
Crash(&cData[0]);
printf("%d\n",cData[1]);
return 0;
}
I expected the program to crash since cData[2] = 100;
(of Crash()) will change the return address of Crash function. I believe that the memory position right next to cData[1](of main()) keeps the return address of Crash function. So after the Crash function finished execution, it will take the value in the return address(which is 100 now) and continue to execute other code. So shouldn't doing so suppose to cause the program to crash?
Upvotes: 0
Views: 115
Reputation: 144605
Your program has undefined behavior, which can be anything, including no crash at all and even expected behavior.
In your particular case, there is a chance the array char cData[2] = {1,2};
occupies space on the stack that is padded with 2 extra bytes before other important pieces of information such as the return address or the saved stack frame pointer. Modifying one of these bytes would have no noticeable effect. Try modifying cData[4]
or cData[8]
, etc. but don't blame me for undesirable side effects.
Upvotes: 1