偶尔使用 C++ 检测到 *** 堆栈崩溃 ***

occasional *** stack smashing detected*** with c++

我有以下用于冒泡排序的 C++ 代码。 这段代码编译没有任何错误,但是当我重新编译并 运行 时,我得到

*** stack smashing detected ***: terminated

作为一个 C++ 新手,我想知道,为什么我在 运行 时偶尔会遇到这些错误?

void bubbleSort(int eatenPanCakes[10],int arrSize){
 
    int temp=0;
    for(int i=0;i<arrSize-1;i++){
        for (int j = 0; j < arrSize-i; j++)
        {
            if (eatenPanCakes[j] > eatenPanCakes[j+1])
            {
                temp = eatenPanCakes[j+1];
                eatenPanCakes[j+1] = eatenPanCakes[j];
                eatenPanCakes[j] = temp;
            }
        }       
    }
}

环境:g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0

我的代码中有一个错误:for (int j = 0; j+1 < arrSize-i; j++) 是正确的算法,并且可以正常工作。

Ref-1,Ref-2

您的程序正在访问超出其大小的数组,这是未定义的行为。检查此 for 循环条件:

for (int j = 0; j < arrSize-i; j++)

[我相信,arrSize 值是 10,因为 eatenPanCakes 数组的类型是 int [10]]

i0时,arrSize-i值为10并且在上一次迭代中当j值为9时,此语句

if (eatenPanCakes[j] > eatenPanCakes[j+1])

访问 eatenPanCakes 数组的 j+1th 元素,它是索引 10 处的元素。请注意,大小为 10 的数组将具有从 09 的有效索引。
相反,for 循环中的条件应该是

for (int j = 0; j < arrSize - i - 1; j++)
                                ^^^

因为第 j 元素与数组中它前面的元素进行比较。