Stack around the variable ' ' was corrupted.

I was working a project that required us to write a console program to add two 10 digit hexadecimal numbers. I've written out the program and everything works fine, but when I exit the program, an error pops up saying "Stack around the variable 'total' was corrupted." I'm not entirely sure what that meant, anyone mind helping out?


Here's a function of the program where I use the variable total[].

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
44
45
46
47
48
49
50
// Function that receives two arrays of hex digits(first and second hexadecimal numbers), computes the sum, and outputs it to the screen.
void addTwoHexadecimalNumbers(const char addendOne[], const char addendTwo[], char total[], const unsigned int size)
{

	char sumDigit, carryDigit = '0', sum_hold, carry_hold; // char variables used to hold the sum digit and carry digit
	int i;


	for (i = 10; i >= 0; i--)
	{
		if (carryDigit == '1')
		{
			carry_hold = carryDigit;
			addTwoHexDigits(carry_hold, addendOne[i], sumDigit, carryDigit);;
			sum_hold = sumDigit;
			addTwoHexDigits(sum_hold, addendTwo[i], sumDigit, carryDigit);
			total[i] = sumDigit;
		}
		else
		{
			addTwoHexDigits(addendOne[i], addendTwo[i], sumDigit, carryDigit);
			total[i] = sumDigit;
		}
		
	}



	if (carryDigit == '1') // if carry digit is equal to '1', then
	{
		cout << "The result is longer than 10 digits. Output: ";
		for (i = 0; i < size; i++)
		{
			cout << "*";
		}

	}
	else
	{
		cout << endl << "The sum of the two hexadecimal numbers is: ";
		for (i = 0; i < size; i++)
		{
			cout << total[i];
		}
	}


	return;

}
It's detecting memory corruption, which is often caused by writing to a bad pointer and/or stepping out of bounds of an array.

In your case, it's probably the latter. And specifically, the debugger is telling you that the corruption occurred around the 'total' variable, so that's a hint that is the array you're stepping out of bounds of.

Looking at the code, I assume 'size' is the size of the 'total' array. In which case I see a problem on line 9.... as you assume size is at least 11.
Oh yes! The size was 10 but I mistaked the 10 as the index. Thank you very much.
Oh yes! The size was 10 but I mistaked the 10 as the index. Thank you very much.


No problem.

But again you probably shouldn't be using '10' here.... you should be using the passed 'size' variable. That's what it's for.
Topic archived. No new replies allowed.