简体   繁体   中英

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; (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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM