简体   繁体   English

为什么程序没有崩溃?

[英]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.

相关问题 缓冲区溢出时程序没有崩溃 - Program didn't crash when buffer overflow 为什么setjmp / longjmp在MinGW中没有时会在MSVC上崩溃? - Why does the setjmp/longjmp crash on MSVC when it didn't in MinGW? 为什么这个程序在init / reboot / shutdown时没有收到SIGTERM? - Why didn't this program receive SIGTERM on init/reboot/shutdown? 为什么我的程序fork函数没有按预期运行 - why my program fork function didn't run as expected 为什么不打印? - Why it didn't print? 为什么 integer 除以零不会使用 gcc 编译的程序崩溃? - Why integer division by zero doesn't crash the program compiled with gcc? 为什么程序在此C编程或unix编程(execvp()系统调用)中不执行某些语句? - Why the program didn't execute some sentences in this C programming or unix programming(execvp() System calls)? 为什么程序在此C编程或unix编程(execvp()系统调用)中不执行某些语句? - Why the program didn't execute some sentences in this C programming or unix programming(execvp() System calls)? 谁能弄清楚为什么我的程序(用C语言)将句子拆分为单词不起作用? - Can anyone figure out why my program (in C) for splitting sentence to word didn't work? 有人可以解释我制作的程序中的错误吗,有人可以解释为什么我不锻炼吗? - Can anybody explain the error in the program i made, can anybody why i didn't workout?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM