I have a function as below
int* readFile(string InputPath)
{
int *myvar = new int[10]; //The file has 10 lines (Using heap)
ifstream inFile;
inFile.open(InputPath.c_str(), ios::in);
if (inFile.fail())
{
cout << "Error reading the input file ";
cout << InputPath << ".";
exit(0);
}
string fileLine;
while (getline(inFile, fileLine))
{
myvar[i]=toint(fileLine); //will be converted to int!
}
;
inFile.close();
return myvar;
}:
How can I free the heap (myvar)?
In general, what is the best method to return such array?
It clearly becomes the responsibility of the caller, to call
delete[]on it. Note that this means the caller has to know that the returned pointer is allocated withnew[], which isn’t exactly optimal.You should return a
std::vector<int>instead, which makes it all so much simpler.