While not related to any of the current issues you have with
your program's operation, there is a basic (and somewhat
common) error in the way you are testing for failure
of the new operator. C++ compilers from many years ago
would generate code that would return NULL if a new
or new[] failed (usually because of insufficient heap
memory available to satisfy the request).
However, for many years now that is not what happens.
Instead, a bad_alloc exception will be thrown if
new/new[] fails. So testing for nullptr after each
new/new[] is pointless as the code will never be
executed (and the pointer will not be set to nullptr
or NULL/null/0).
To have new/new[] return a nullptr instead of throwing
an exception you must use the nothrow version:
new(std::nothrow) ...
So if you want your code to actually work as written
in the event of an allocation failure you must change
all of your new statements to use that form.
"If there's insufficient memory for the allocation request,
operator new throws a std::bad_alloc exception. Or, it returns
nullptr if you've used the placement form new(std::nothrow),
or if you've linked in non-throwing operator new support.
For more information, see Allocation failure behavior."
new and delete operators
https://learn.microsoft.com/en-us/cpp/cpp/new-and-delete-operators?view=msvc-170
Also see:
new operator (C++)
https://learn.microsoft.com/en-us/cpp/cpp/new-operator-cpp?view=msvc-170
By way of an example which illustrates both behaviours,
you can build this small program and run it with a
breakpoint set on the return statement. Try it first with
the statement:
cpp = new char*;
Check the output in the console window.
Then rebuild it using the nothrow version:
cpp = new (nothrow) char*;
Check the output in the console window.
#include <iostream>
using namespace std;
int main()
{
int n;
char ** cpp = nullptr;
for (n = 0; n < 2000000000; ++n)
{
try{
cpp = new char*; // throws a bad_alloc exception
//cpp = new (nothrow) char*; // returns nullptr
}
catch (std::bad_alloc)
{
cout << "new failed! (bad_alloc)" << endl;
break;
}
if (cpp == nullptr)
{
cout << "new failed! (nullptr)" << endl;
break;
}
}
return 0;
}