指针的释放方式
#include <stdio.h> #include <stdlib.h>
#include <malloc.h>
#include <assert.h>
double *Alloc_Double_Array(long length)
{
double *array = NULL;
if( NULL == (array = new double [length]) )
{
fprintf(stdout, "Merory Exhausted\n");
return NULL;
}
//memset(array, 0, length*sizeof(double));
return array;
}
template <typename T>
void Free_Array (T **array)
{
assert( array != NULL);
//printf("array=0x%p,*array=0x%p\n",array,*array);
delete *array;
} // Free_Array(&p1);
template <typename T>
void FreeArray (T *array)
{
assert( array != NULL);
delete *array;
} // Free_Array(&p2);
int main()
{
double *p1 = Alloc_Double_Array(0x100);
double *p2 = Alloc_Double_Array(0x100);
printf("p1=0x%p,p2=0x%p\n",p1,p2);
p1[0] = 1.3;
p2[0] = 2.3;
Free_Array(&p1);
printf("first\n");
p1 = Alloc_Double_Array(0x100);
p1[0] = 1.3;
p2[0] = 2.3;
printf("p1=0x%p,p2=0x%p\n",p1,p2);
FreeArray(&p2);
printf("second\n");
p2 = Alloc_Double_Array(0x100);
p1[0] = 1.3;
p2[1] = 2.3;
printf("p1=0x%p,p2=0x%p\n",p1,p2);
return 0;
}
为什么采用上述两种方法释放指针均正确》》