如果打印后输入整数,则C++分段故障,但其他情况下可以

C++ Segmentation Fault if integer is input after printed, but ok otherwise

本文关键字:故障 其他 情况下 分段 C++ 打印 输入 整数 如果      更新时间:2023-10-16

以下源代码编译并运行精细

#include <cstdio>
#include <iostream>
using namespace std;
int main() {
    int t;
    cout << t << endl; // the seg fault / rte is for this
    cout << t+10 << endl;
    int mat[0];
    int mat2[t+10];
    for (int i = 0 ; i<100 ; i++) {
        //cout << mat[i] << endl;
    }
    cout << sizeof(mat)/sizeof(int) << endl;
    cout << sizeof(mat2)/sizeof(int) << endl;
    //cin >> t;

    return 0;
}

但是,如果我取消注释cin >> t,则会导致Segmentation Fault。

#include <cstdio>
#include <iostream>
using namespace std;
int main() {
    int t;
    cout << t << endl; // the seg fault / rte is for this
    cout << t+10 << endl;
    int mat[0];
    int mat2[t+10];
    for (int i = 0 ; i<100 ; i++) {
        //cout << mat[i] << endl;
    }
    cout << sizeof(mat)/sizeof(int) << endl;
    cout << sizeof(mat2)/sizeof(int) << endl;
    cin >> t;

    return 0;
}

里面发生了什么?

我发现有问题

#include 
#include 
using namespace std;
int main() {
    int t;
    cout << t << endl; // the seg fault / rte is for this
    cout << t+10 << endl;
    int mat[0];
    int mat2[t+10]; // <=== HERE IS THE PROBLEM
    for (int i = 0 ; i<100 ; i++) {
        //cout << mat[i] << endl;
    }
    cout << sizeof(mat)/sizeof(int) << endl;
    cout << sizeof(mat2)/sizeof(int) << endl;
    cin >> t;

    return 0;
}

您正在创建一个可变大小的数组,这没有问题,但您是基于未初始化的变量定义大小的。C/C++上未初始化的局部变量,没有默认值,它可以具有从堆栈垃圾中获得的ANY

为了测试这一点,我用奇怪的(但可能的)t值编译了程序,以获得SegmentationFaults:

int main() {
    int t = -22;
    ...
    int mat[0];
    int mat2[t+10];
int main() {
    int t = 0xdeadbeef;
    ...
    int mat[0];
    int mat2[t+10];

你可以得到任何一个值,但它会随机失败,我使用cin>>t会在编译器优化中更改某些变量,从而导致堆栈值或类似的事情,但这是完全不可预测的,你可以认为它几乎是随机