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.
_______________________________________________
Help-gplusplus mailing list
[email protected]
http://lists.gnu.org/mailman/listinfo/help-gplusplus

Reply via email to