I have a function like
template <class Type>
myFunc(Type** arrayToBeFilled);
I call it like this:
double* array = NULL;
myFunc(&array);
And inside the function I do some reading and parsing numbers with strtod function:
//Here comes file opening, getting number of lines and number of doubles in every line
...
char *inputString = new char[LONG_STRING_SIZE];
char *pNext = NULL;
(*arrayToBeFilled) = new Type[length*rowSize];
for (int i=0; i<length; i++)
{
source.getline(inputString, LONG_STRING_SIZE);
pNext = NULL;
for (int j=0; j<rowSize; j++)
{
double d = strtod(inputString, &pNext);
(*arrayToBeFilled)[i*rowSize+j] = d;
inputString = pNext;
pNext = NULL;
}
}
Variable d is just for check with debugger – and it’s just fine while running.
But after filling the array I try to print it (just for check)
for (int i=0; i<length; i++)
{
for (int j=0; j<rowSize; j++)
{
cout<<(*arrayToBeFilled)[i*rowSize+j]<<" ";
}
cout<<"\n";
}
And here comes bad output – other numbers, sometimes heap corruption and so. I was printing it in and out of the function – the same results. And I can’t delete this array no or neither out the function – run time errors follow me!
Why do you use raw C arrays in C++? If you use STL classes like
std::vectorinstead of rawnew[], your code will become cleaner, simpler to read and maintain (for example, you don’t need explicitdelete[]calls: the destructor will cleanup heap memory). In general, in modern C++ the rule is “if you are writing new or delete, you are doing it wrong” (with some exceptions).Note also that with C++11 move semantics, you can simply return the
vectorinstead of using output reference/pointer arguments:Inside your function body, instead of your code
just write:
and then simply
return arrayToBeFilled;.(Note also that
vector‘s can be nested together: you may also usevector<vector<Type>>to make a 2D array, but this is less efficient than a singlevector<Type>, which more directly maps to your rawnew[]call.)In addition, in the code you posted you create a raw C array on the heap with
new char[LONG_STRING_SIZE]and assign the pointer to it toinputString; then you modifyinputStringwith an assignment frompNext: but in doing so, you leak the initial array whose pointer was stored ininputString.