new - delete question

why in (1) delete [] d; causes crash but not n (2)?.
what is the best to write this piece?.
/////////(1)
d = new double[n];
for (int i = 0; i < n; i++)
{
*d = i;
d++;
}
delete [] d;

//////////(2)
d = new double[n];
for (int i = 0; i < n; i++)
{
d[i] = i;
}
delete [] d;
[398 byte] By [pharma] at [2007-11-18 19:28:14]
# 1 Re: new - delete question
Originally posted by pharma
why in (1) delete [] d; causes crash but not n (2)?.
what is the best to write this piece?.
/////////(1)
d = new double[n];
for (int i = 0; i < n; i++)
{
*d = i;
d++;
}
delete [] d;
In the first example, you are changing the value of d when you say "d++". It no longer points to the original location of the allocation. When you call new[], you must delete[] the same value.

Regards,

Paul McKenzie
Paul McKenzie at 2007-11-9 0:32:32 >
# 2 Re: new - delete question
To expand on Paul's response,

Add 2 lines to make it work

d = new double[n];
double *Old = d;
for (int i = 0; i < n; i++)
{
*d = i;
d++;
}
d = Old;
delete [] d;
cvogt61457 at 2007-11-9 0:33:34 >
# 3 Re: new - delete question
cvogt61457, final touch:
instead of last assignment + delete,
delete [] Old;
is sufficient.
Guysl at 2007-11-9 0:34:33 >