I have an integer array sorting program here but I have a problem: whenever I run the program I sometimes get a “The stack around the variable ‘numbers’ was corrupted” message and sometimes it just repeatedly prints out the number 8. Here’s my code (compiled in Visual C++ 2010):
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
void swap(int *x, int *y)
{
int tmp=0;
tmp = *x;
*x = *y;
*y = tmp;
tmp = 0;
}
int main()
{
int numbers[13] = {8,16,23,487,2,301,48,0,13,10,644,12};
int size = sizeof(numbers) / sizeof(int);
//sort
int i = 0;
int* a = &numbers[0];
int* b = &numbers[1];
while(i < size){
if(*a > *b){
swap(a, b);
}
*a++;
*b++;
i++;
}
//Print our results
int loopIterator = 0;
int numToPrint = 0;
while(loopIterator < size){
cout << numbers[numToPrint] << endl;
loopIterator++;
}
system("PAUSE");
}
First, you never increment
numToPrint, therefore you are never going to print more than the value ofnumbers[0]. At the very least change your code to:Secondly, since your
whileloop uses the testi < size, you are, on the last iteration of the loop, going to be accessing memory outside ofnumbersfor yourbpointer, and possibly swapping that value into the last slot ofnumbers(i.e., whereais pointing to). You want to change your test toi < (size - 1)to avoid that scenario. For instance, if ati == 0you havea = &numbers[0]andb = &numbers[1], then by the time thati == 12, you are going to end up witha = &numbers[12]andb = &numbers[13]… the value thatbis pointing to in this instance is past the end of the array. Depending on how your compiler has setup the stack, and the way you’ve allocatednumberson the stack, this could actually play some havoc with your program should you end up withbpointing into the activation record data-structures for yourmain()function, and in-turn corrupting it.