Dear all,
I started a program with pointers. There seemed to be a problem with memory leak that I did not know how to fix properly.
I had to create an array of random numbers. I wrote a function that returns a pointer pointing to those values:
1 2 3 4 5 6 7 8 9 10 11
//Create a pointer that points to a random double array:
double* runif(constdouble min = 0.0,constdouble max = 1.0, constint n = 1)
{
double* pdata;
pdata = newdouble [n];
for (int k = 0; k < n; k++)
{
*(pdata + k) = rand()*(max - min)/RAND_MAX + min;
};
return pdata;
};
But now I see that if I call that function from the main function twice, there will be a problem, for example:
1 2 3 4 5 6 7 8
int main()
{
srand(time (NULL));
double* prand;
prand = runif(0.0,1.0,20);
//Do some things//
prand = runif(0.0,1.0,30);
}
The 20 double array in the first call should have been lost. I may do "delete prand;" before calling the new time, but I wonder is that the proper way of avoiding this issue?
I would wish to have your helps. Thank you in advance.