Run-time check failure #2:Stack around the variable 'slot' was corrupted.

I'm running this code but I'm getting an error that I can't seem to fix. However, my code compiles and I get an output, but it is incorrect.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include<iostream>
using namespace std;
int swap(int[], int, int);
int main(){
	int slot[10] = { 100.10, 334.60, 290.80, 410.70, 600.00, 732.90, 870.92, 100.70, 590.89, 979.00 };
	int n = 10, i;
	int lower, upper, sortflag, sml, scan;
	lower = 0;
	upper = n - 1;
	sortflag = 1;
	while ((lower < upper) && (sortflag == 1)){
		sml = lower;
		sortflag = 0;
		scan = lower + 1;
		while (scan <= upper - lower){
			if (slot[scan]>slot[scan + 1]){
				swap(slot, scan, scan + 1);
				sortflag = 1;
				if (slot[scan] < slot[sml])sml = scan;

			}//IF
			scan++;

		}//WHILE
		swap(slot, lower, sml);
		upper = upper - 1;
		lower = lower + 1;

	}//WHILE
	cout << "ALEXANDRA'S NETPAY SORT:" << endl;
	for (i = 0; i < n; i++)cout << slot[i] << "";
	cout << endl;
	return 0;
}//MAIN

int swap(int slot[], int i, int j){
	int temp;
	temp = slot[i];
	slot[i] = slot[j];
	slot[j] = temp;
	return 0;
	system("pause");
}//SWAP 
Last edited on
On line 15 we see that scan can be equal to upper when lower is 0 and the body of the loop controlled by that expression will execute. When that is the case slot[scan+1] is out of the bounds of the slot array. Likewise, your swap function will access and modify memory outside the bounds of the array when invoked on line 17.
Thank you for the quick reply. So would I set the slot array differently on line 17?
Topic archived. No new replies allowed.