Skip to main content
gamedev.net
🔒 Locked

corrupted stack?????

Started by cdbabcock 3 replies 650+ views
Original Post
cdbabcock
cdbabcock
Hello again and no this isnt about those **** and blanks. I have posted the code below and this is actually right out of the book, when i compile and run using Visual Studio 2005, i get a msg saying "Stack around the variable "sum" was corrupted.

#include <iostream>
using namespace std;

int main(){

	int array0[7] = {1,2,3,4,5,6,7};
	int array1[7] = {-9,-8,-7,-6,-5,-4,-3};
	int sum[7];
	for (int i=0; i < 7; ++i){
		sum[7]= array0 + array1;
		cout << array0 << " + " << array1 << " = ";
		cout << sum << endl;
	}
}

The output is incorrect as well: 1 + -9 = -858993460 2 + -8 = -858993460 and so on, they all equal that large negative number. What did i do wrong or how can i fix this.
SiCrane
SiCrane
I don't think you want sum[7] inside your loop.
Evil Steve
Evil Steve
sum[7] is outside your array. sum only has indices ranging from 0 to 6.
jflanglois
jflanglois
It should be:
sum= array0 + array1;


jfl.

edit: Like Evil Steve said, sum[7] is out of bounds, which is why the stack was being corrupted.
Conner McCloud
Conner McCloud
To expand a bit on what they said, in debug builds [which VS defaults to] a lot of extra checks are performed for you in the background. One common check is that extra memory is allocated around your objects. This memory is set to some known value [I seem to recall VC++ using 0xCDCDCDCD, but it doesn't really matter], and later the program verifies that the memory is still that same value. If it has changed, then your code has gone out of bounds somewhere, and it alerts you to that.

There is a corresponding error that refers to a corrupted heap that comes into play when you are using dynamic memory. The same basic idea applies

This is what your message is saying. 9 times out of 10, those errors are the result of going out of bounds on your arrays. So anytime you see it, that should be your first instinct...check your array usage, and make sure you haven't done anything foolish.

CM

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.