+ 1

how to make sure a dynamic variable is removed in C++?

I had created some dynamic variable in a C++ code. When I had decided to check that the variable is deleted or not, I saw that I still can use it ! For example, in this code : #include <iostream> using namespace std; int main () { int *p=new int; *p=3; delete p; cout<<*p; return 0; } The output still is 3 ! What's the problem ?

11th Mar 2024, 9:19 PM
Sanan
4 odpowiedzi
+ 3
The output is not necessarily 3. For me it outputs a number which i suppose is the memory of the pointer. If you want to deallocate the memory that the pointer points to, you must nullify the pointer after deleting it.
11th Mar 2024, 9:36 PM
Black Winter
0
(Black Winter)I tested it many times with different compilers but most of the time the pointer wasn't deleted
11th Mar 2024, 11:38 PM
Sanan
0
you cannot actually delete a pointer. what you are deleting is the allocated space created by new. have you tested the code in Sololearn? I am using the app version and it is not displaying 3 after the delete. what it points to after delete is undefined behavior so it's compiler dependent. It may still point to 3 or some other value. That is why you must set your pointer to nullptr to prevent future use. delete p; p = nullptr; an error will be raised if you try to use it again.
12th Mar 2024, 12:25 AM
Bob_Li
Bob_Li - avatar
0
*3 no 3 yes
13th Mar 2024, 7:04 PM
Yako Vodila
Yako Vodila - avatar