(moving/expanding from the comments)
Since you are allocating a new array every time without deallocating it, you have a massive memory leak, i.e. you continue to ask memory to the system without ever giving it back. Eventually the space on the heap finishes, and at the next allocation all you get is a std::bad_alloc
exception.
The "C-style" solution would be to remember to deallocate such memory when you don't need it anymore (with delete[]
), but, this is (1) error-prone (think e.g. if you have multiple return paths inside a function) and (2) potentially exception-unsafe (every instruction becomes a potential return path if you have exceptions!). Thus, this way should be avoided.
The idiomatic C++ solution is to use either smart pointers - small objects that encapsulate the pointer and deallocate the associated memory when they are destroyed - or standard containers, that do more or less the same thing but with copy semantics and some more bells and whistles (including storing the size of the array inside them).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…