Hi,
Hope U must B doing well.
I have a problem please help me in sorting out the same.
I have created a dynamic integer Array and initialized its values.
After its use I have deleted the same.
Still den it gives me the stored values of all the elements except the first one, as it is resetting the first element to '0'. Why not the others?
The memory is being deallocated. Your for() loop after the delete [] a is accessing free memory at that point, which can have any value. The C/C++ runtime library does not zero out memory that is freed via delete or free(). [That the first element appears to be zeroed out is a remnant of C's malloc() function inserting the memory block into a free list. malloc() actually uses a portion of the memory block as next and prev pointers (among other things) to maintain a list of free memory blocks.]
Thnx Smith,
Is there any function by which we zeroed the memory location
or
we have to memset the location to zero prior to deleting/freeing the memory.
Another query...
Is it a good practice to assign the pointer to zero after deleting/freeing the memory like ...
If you want the memory zeroed before it is freed you'll need to do it yourself.
memset() or bzero() will work in each case as long as you know the size of the memory block being freed. Another possibility is to override the global new and/or delete functions to zero the memory prior to allocating or deallocating. This will catch ALL new/delete calls in your code, but wouldn't catch any memory allocated or freed directly with malloc/realloc/calloc or free.
To answer your second question, it depends upon the lifetime (scope) of a. If the variable a isn't going out of scope immediately, then you might consider setting it to 0 as a way of tracking down bugs related to use of a after it has been deleted. If it's the last lines in a function and a is a local variable, then don't bother. If a is a member of a class and the delete is in the destructor, then a's lifetime is only to the end of the destructor, so again don't bother. It all comes down to how long the variable remains in scope after the memory has been freed.