C++:运行-时间检查失败;堆栈变量损坏;也因一个错误而关闭

C++: run-time check failure; stack around variable corrupted; also off by one error

我花了一个多小时试图找出我写的这个插入排序代码中的错误。问题在于,即使它对数组进行了排序,它也会将其值向上移动一位。例如,input[2] 给出 2 而不是 1。之后我得到 运行-time error: "stack around variable was corrupted." 这可能是一个循环错误,但我无法找到它。感谢您的帮助。

//Haris
#include <iostream>

using namespace std;

void insertionSort(int*, int);

int main(){

    int input[10] = { 8, 1, 5, 2, 6, 3, 10, 9, 4, 7 };
    insertionSort(input, 10);
    cout << input[2] << endl;// results are off by one, so input[2] is 2 instead of 1
    system("pause");
}

void insertionSort(int input[], int size){

    int temp = 0;//supposed minimum that is being checked
    int temp1;//value of array that is being replaced by temp
    for (int i = 0; i < size; i++){
        if (input[i] > input[i + 1]){
            temp = input[i + 1];
            int location = i + 1; //location of the supposed minimum
            for (int j = i + 1; j > 0; j--){
                if (temp < input[j - 1]){
                    temp1 = input[j - 1];
                    input[j - 1 ] = temp;
                    input[location] = temp1;

                    //cout << "[j-1] is " << j - 1 << endl;
                    //cout << "input[j-1] is " << input[j - 1] << endl;
                    //cout << "input[location] is " << input[location] << endl;
                    //cout << "location is " << location << endl;

                    location = (j - 1);

                }
            }
        }
    }
}

i == size - 1:

时,您将越界
for (int i = 0; i < size; i++){
    if (input[i] > input[i + 1]){
    //                  ^^^^^^^ i + 1 == size -> out of bounds

改为

for (int i = 0; i < size - 1; i++){

在外循环中,您正在访问超出限制的内存区域。
试试这个:

#include <iostream>

using namespace std;

void insertionSort(int*, int);

int main()
{

    int input[10] = { 8, 1, 5, 2, 6, 3, 10, 9, 4, 7 };
    insertionSort(input, 10);
    cout << input[2] << endl;// results are off by one, so input[2] is 2 instead of 1
    system("pause");
}

void insertionSort(int input[], int size)
{
    int temp = 0;//supposed minimum that is being checked
    int temp1;//value of array that is being replaced by temp
    for (int i = 1; i < size; i++){
        if (input[i] < input[i - 1]){
            temp = input[i];
            int location = i; //location of the supposed minimum
            for (int j = i; j > 0; j--){
                if (temp < input[j - 1]){
                    temp1 = input[j - 1];
                    input[j - 1 ] = temp;
                    input[location] = temp1;

                    //cout << "[j-1] is " << j - 1 << endl;
                    //cout << "input[j-1] is " << input[j - 1] << endl;
                    //cout << "input[location] is " << input[location] << endl;
                    //cout << "location is " << location << endl;

                    location = (j - 1);

                }
            }
        }
    }
}