first,i do not suggest write like this.
i usually write like this
void readfile(string InputPath,char* ReturnedPointer)
{
...
return ;
}
and the ReturnedPointer to be dealed outside of the function.
vector<int> readFile(const string& InputPath)
{
ifstream inFile(InputPath); // or inputPath.c_str() for old compilers
if (!inFile)
{
cout << "Error reading the input file " << InputPath << ".";
exit(0); // thow would be better! Or at least return an empty vector.
}
vector<int> myvar;
for(int n; inFile >> n && myvar.size() < 10; )
{
myvar.push_back(n);
}
return myvar;
}
But if you really really want to use new[], then at least return the self-managing pointer, std::unique_ptr<int[]>. Never let a raw pointer escape a function, not in C++.
The int* you return; don't change it, don't lose it, and when you're done with the memory,
delete [] theReturnedPointer;
Unless you've got a really good reason for making it an array, you could save yourself the bother of memory management and just use a vector.
So, myvar pointer can be easily deleted in my main program by adding delete[] theReturnedPointer.
if so,
But if you really really want to use new[], then at least return the self-managing pointer, std::unique_ptr<int[]>. Never let a raw pointer escape a function, not in C++.
What is the problem with previous code (delete[] theReturnedPointer)?
Does the compiler realise the heap correctly and delete it without any problem?
I see. The examples are not exception safe. So yes, they're incorrect in that respect. But they are illustrating how to construct multi-dimension arrays, so you have to take what you can from the them.
Your real problem is one of design that happens to have technical problems too. Like I said, there's no way know the size of the array being passed back from you function. No one can use an array unless the size is known, for all the caller knows the size could be zero.
So, in addition of sending an array, the size of array in all dimensions must be send as well, and using delete just have exception problem, and will not cause memory leakage after deleting heap outside the function.
and using delete just have exception problem, and will not cause memory leakage after deleting heap outside the function
I'm not sure what you mean, but the delete must match the allocation.
^Actually, you probably want to pass in a parameter to the FreeDynamicArray function so it can actually delete the correct number of rows. Right now, it's deleting ROW loops which may be different than the number you have allocated with AllocateDynamicArray.