Memory leak?

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(const double min = 0.0,const  double max = 1.0, const int n = 1)
{
	double* pdata;
	pdata = new double [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.
You can use delete to deallocate the memory block.
You can't, you have to use delete[] when you used new[] to allocate it.
Yeah, thanks... I will be more careful.
Topic archived. No new replies allowed.