-1

I have a problem with a destructor in a class that I created.

My constructor looks like this:

chess_b = new int*[N];
for (int i = 1; i <= N; i++)
     chess_b[i] = new int[N]; 

and detructor like this:

for (int i = 1; i <= N; i++)
    delete[] chess_b[i];

delete[] chess_b;

There are times eeerything works fine, but it crashes a lot and when I try to debug it points to this line of code:

delete[] chess_b[i];

I've tried using this-> but it didn't work either.

Thanks for help in advance.

  • 2
    If you have a destructor, do you follow [the rules of three or five](http://en.cppreference.com/w/cpp/language/rule_of_three)? Though I recommend you start using [`std::vector`](http://en.cppreference.com/w/cpp/container/vector) and follow the rule of zero. – Some programmer dude May 22 '18 at 14:35
  • 3
    C++ uses `0` based indexing, not from `1`. So valid indexes are `[0]` to `[N-1]` the last iteration in your loop goes out of bounds – Cory Kramer May 22 '18 at 14:35
  • Or it could just be that you need [a few good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) instead, or reread your class-notes. – Some programmer dude May 22 '18 at 14:35

2 Answers2

1

your for loop should be 0 to N-1, not 1 to N

code707
  • 1,663
  • 1
  • 8
  • 20
0

The indexes in C++ must be from 0 to N-1:

for (int i = 0; i < N; i++)
273K
  • 29,503
  • 10
  • 41
  • 64