-2

Why does this code executed in debug mode trigger a breakpoint?

#include <list>

void main() {

  std::list<int>::iterator* iterators = new std::list<int>::iterator[50];

  delete iterators;

}
acco93
  • 128
  • 2
  • 11
  • 4
    What do you mean by breakpoint – Xatyrian Jan 24 '18 at 14:18
  • 13
    change to `delete []` – PiotrNycz Jan 24 '18 at 14:19
  • An exception (iterators.exe has triggered a breakpoint.) – acco93 Jan 24 '18 at 14:20
  • 1
    `delete [] iterators;` – iBug Jan 24 '18 at 14:20
  • 1
    What is `void main()`? It's *ancient*. – iBug Jan 24 '18 at 14:20
  • *Why does this code executed in debug mode trigger a breakpoint?* -- Ok, I have to ask the question -- does your real code actually do things like this? – PaulMcKenzie Jan 24 '18 at 14:24
  • Forgive me the 'void main' it was just to write a code snippet, thanks for the answers. I have to store some linked list element pointers, do you have a better way to do it? I know that they might be invalidated by some operations but I need to know given an element where it is placed in the list. – acco93 Jan 24 '18 at 14:25
  • 1
    @acco93 *I have to store some linked list element pointers, do you have a better way to do it* -- `std::vector::iterator> iterators(50);` Then there is no need for `delete []`, – PaulMcKenzie Jan 24 '18 at 14:28

2 Answers2

3

As said in comments, if you instantiate an array using

... = new name[];

you must use

delete [] name;
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
Benjamin Barrois
  • 2,566
  • 13
  • 30
2

When you use the operator new[] you must also use the operator delete[], otherwise it is an undefined behavior.

You can check this question for more information: Is delete[] equal to delete?

Sebi
  • 428
  • 5
  • 11