Salut tout le monde,
If an allocation happens with the new operator we have to deallocate the allocated memory which happens with delete. |
First of all you should not use these two operators which are a source of problems in C++ and even the standard library strongly advises against it unless you have a sharp knowledge of the subject.
Since C++11 you shouldn't need these two operators (new and delete), because you can use smart pointers.
Here are the causes:
* it is much more difficult to manage the FREE STORE or the HEAP by yourself, it is better to leave this task to the standard library instead.
*It is difficult to know if we are releasing memory at the right time.
*We forget to free the memory - in which case we have a memory loss.
*We free the memory while pointers are still referring to that memory - in which case we have a pointer that refers to a memory that is no longer valid.
As far as I'm concerned deallocation means freeing that allocated memory for new allocations. Fine up to here. |
Not really, in truth deallocation in C++ means:
1) Destruction of the dynamically allocated object.
2) Finally freeing the space that the dynamically allocated object occupied in memory .
But the pointer (named now dangling) still keeps the that address. Right?
|
In fact when we apply the delete operator on a pointer that was previously returned by the new operator, the compiler does the deallocation (destroying the dynamically allocated object and freeing its space in the free store), the compiler will make our pointer into a float pointer, that is to say, a float pointer is a pointer that was pointing to a memory space that used to contain an object but no longer does. So you understand that even if you use the delete operator on the pointer, it still contains the address in memory that has been destroyed, so if you dare to use a pointer on which the delete operator has already been applied, the compiler may throw an exception or there will simply be an undefined behavior. Do you understand so far?
Well, let's continue, since I answered your question, so how to solve this problem of float pointer?
You just have to make your pointer null, that is to say give a null value to your pointer.
Before C++11:
type *ptr = NULL;
Since C++11:
type *ptr = nullptr; //(this is recommended by the standard library).
Note: I know I was a bit long but it was worth it for a good understanding and importance of using smart pointers instead of embedded pointers