堆栈上价值的腐败

Corruption of value on the stack

本文关键字:堆栈      更新时间:2023-10-16

在下面的代码中,我发现在阅读了一定数量的输入后,N的值被替换为(至0(。我相信这是因为我在堆栈上分配了K和S数组。我想知道我的结论是否正确?我曾经在C中很长一段时间在C中进行编码,然后切换到Python和其他脚本语言。因此,我的内存管理似乎已经折腾了。

ofstream cop("op1.txt");
ifstream cinp("in1.txt", ios::binary);
int T, t=1;
cinp >> T;
for(;t <= T;t++){
    fflush(stdin);
    long D;
    int N;
    long K[N], S[N];
    cinp >> D >> N;
    double times[N], max = 0;
    cout << D << " " << N << endl;
    for(long i=0; i<N; i++) {
        cout << D << " " << N << endl; // Output of this line is shown below till N gets replaced by 0
        cinp >> K[i] >> S[i];
        times[i] = (1.0 * (D - K[i]))/S[i];
        if(max < times[i])
            max = times[i];
    }
    cout << D << " " << N << endl;
    if(t == 3) {
        cout << D << " " << N << endl;
        for(int i=0;i<N;i++)
            cout << K[i] << " " << S[i] << endl;
    }
    cop << "Case #" << t << ": " << std::setprecision(6) << std::fixed << D/max << endl;
}

一瞥何时被替换

912786011 100 <--- Needs to read 100 nos as N is 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 0 <---------------- Became 0

另外,我想知道我的结论是否正确,那么可以在堆栈上分配的大量内存(没有新的(?

deidei正确地说,您已经错误地使用了GCC的VLA扩展。

https://gcc.gnu.org/onlinedocs/gcc/variable-length.html

分配存储时,计算一次数组的长度一次 并在阵列的范围内被记住,以防万一您访问它 使用大小。

因此,您必须分配(并务必确保它(在声明数组之前,用于大小的变量具有正确的价值。您没有,并且您脱离了数组的束缚,在堆栈中读取数据。如果这是一个函数,则很可能是从函数退出时会触发运行时错误。

可变长度是此功能的错误称为,因为生成的数组无法更改大小,因此其使用情况非常有限。最好使用STD :: vector,您可以保留提供的尺寸。VLA在C99中允许使用,但不是C 中的标准配置,它们不适合其他C 编译器。