help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: question about "new" and "delete" ?


From: Mike - EMAIL IGNORED
Subject: Re: question about "new" and "delete" ?
Date: Sat, 05 Mar 2005 22:40:39 -0500

jack wrote:
> 
> the following code can be run and can generate result:
> a[9]=10;
> what happend there?
> int main()
> {
>   double *a= new double[10];
>   for(int i=0;i<10;i++){
>     a[i]=i+1;
>   }
>   delete [] a;
>   cout << a[9] << endl;
>   return 0;
> }

You freed the memory, and thereby made it available to the
system for other use.  Unfortunately, nothing else in the
system used it, so you got the 10.  I say "unfortunately",
because next time you might not get the 10.  This is a
common kind of error that has lead to much unreliable
software.  To prevent the problem, I always follow
a delete by clearing the pointer:

   delete [] a;
   a = 0;

Your cout will then result in an immediate, and obvious
crash, which can then be debugged.

Mike.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]