Why is this corrupting the stack?

I have an array of integers, and an array of booleans in which I'm trying to set the boolean values to true to a corresponding integer value.

For example in the int array { 5, 2, 20, 4, 13, 256 }
the bool array[5],[2],[20], etc will be true.

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
#include <iostream>

using namespace std;

class IntegerSet {
public:
	IntegerSet::IntegerSet(const int arr[], int n) {
		for (int i = 0; i < 256; i++) {
			set1[i] = false;
		}
		for (int i = 0; i < n; i++) {
			int num = arr[i];
			set1[num] = true;
		}
	}

private:
	bool set1[256];
};



int main() {
	int arr1[6] = { 5, 2, 20, 4, 13, 256 };
	IntegerSet s3(arr1, 6);

	return 0;
}


This code however is corrupting the stack.
For an array of size 256, the last valid index is 255. You are using an index of 256 for such an array which is out of bounds, resulting in undefined behavior.
A silly mistake on my behalf, thank you.
Topic archived. No new replies allowed.