[英]Why didn't the program crash?
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;
我预计程序会崩溃,因为cData[2] = 100;
(of Crash()) will change the return address of Crash function. (of Crash())将更改Crash函数的返回地址。 I believe that the memory position right next to cData[1](of main()) keeps the return address of Crash function. 我相信,紧挨着cData [1](main())的内存位置保留了Crash函数的返回地址。 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. 因此,当Crash函数执行完后,它将取返回地址中的值(现在为100),并继续执行其他代码。 So shouldn't doing so suppose to cause the program to crash? 难道不应该这样做导致程序崩溃吗?
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};
在您的特定情况下,有可能数组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. 占用堆栈上的空间,并在其他重要信息(例如返回地址或保存的堆栈帧指针)之前填充2个额外的字节。 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. 尝试修改cData[4]
或cData[8]
等,但是不要怪我有不良的副作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.