Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

About dynamic memory allocation

Status
Not open for further replies.

mrhegemon

Programmer
Jul 3, 2003
20
US
Are you not allowed to use the delete[] operator on an array that was dynamically allocated in a function with new?

e.g.,

Code:
void func1()
{
   ...

   double *a;

   func2(a);

   delete[] a;

   ...
}

void func2(double *a)
{
   ...

   a = new double[N];

   ...
}

I am confused about this. It seems to work in part of my code, but leads to segmentation faults in others.
 
Yes, you can use delete[] as you have, the problem is that you need to pass the address of your pointer a to func2 (pass by reference rather than by value):

Code:
void func1()
{
   ...

   double *a;

   func2(&a);

   delete[] a;

   ...
}

void func2(double **a)
{
   ...

   *a = new double[N];

   ...
}
 
itsgsd is right, but for the fun of it here's the same using a reference to a pointer instead of a double pointer. It makes it a little easier to call and use inside the funtion.
Code:
void func1()
{
   ...

   double *a;

   func2(a);

   delete[] a;

   ...
}

void func2(double *&a)
{
   ...

   a = new double[N];

   ...
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top