I can't understand the end of this code (array = 0;
):
#include <iostream>
int main()
{
std::cout << "Enter a positive integer: ";
int length;
std::cin >> length;
int *array = new int[length];
std::cout << "I just allocated an array of integers of length " << length << '\n';
array[0] = 5; // set element 0 to value 5
delete[] array; // use array delete to deallocate array
array = 0; // use nullptr instead of 0 in C++11
return 0;
}
At the end, a dynamically allocated array is deleted (returned to OS) and then assigned a value of 0.
Why is this done? After array has been returned to the OS, there is no need to assign it a value of 0, right?
Code from: http://www.learncpp.com/cpp-tutorial/6-9a-dynamically-allocating-arrays/
You're right it is not needed because the memory is freed (deallocated) by the operator
delete
. But think of a case where you may use the pointer in another place in your code (functions, loops, etc.) after you usedelete[]
on it.The
array
variable still holds the address of the old allocation after thedelete[]
statement was called (dangling pointer). If you would access that address you would get undefined bahaviour (UB) because the memory is no longer yours, in most of the cases your program would crash.To avoid that you do a null pointer check like:
which is checking the pointer against the address 0 which represents an invalid address.
To make that check possible you set the pointer to
nullptr
orNULL
if C++11 is not available. Thenullptr
keyword introduces type safety because it acts like a pointer type and should be preferred over the C-likeNULL
. In pre C++11NULL
is defined as integer 0, since C++11 it's an alias tonullptr
.To define your own
nullptr
to use it for pre C++11 compiler look here: How to define our own nullptr in c++98?An interesting fact about
delete
ordelete[]
is that it is safe to use it on anullptr
. It is written at point 2 on cppreference.com or at this SO answer.