0

explain the last line of output

deleting pointer from.heap meaning? https://code.sololearn.com/cLolR7k33Pe7/?ref=app

5th Jul 2017, 1:49 AM
Krupesh Anadkat
Krupesh Anadkat - avatar
9 Respostas
+ 8
as you have deleted the pointer p now points nowhere. The value it prints is random junk.
5th Jul 2017, 2:00 AM
jay
jay - avatar
+ 7
@Krupesh; it frees up that memory address for reuse. p still has the memory address, it points to something else or nothing. thus the problem. To make deleting pointers safe'r' empty the pointer *p = nullptr; after deleting it or use smart pointers. edit: empty the pointers "after" deleting them.
5th Jul 2017, 4:00 PM
jay
jay - avatar
+ 6
** Just to clarify incase you didnt get notified of the edit. delete p; *p = nullptr;
5th Jul 2017, 4:40 PM
jay
jay - avatar
+ 2
Yes and that's why pointers are dangerous if you use them badly. When you create a pointer, it automatically points on something in the memory. If you don't attribute something of your code, it can point on anything in the memory ! Such as another variable necessary to an other programm... Then if you do '(*p)++', the programm can crash. If it is part if the operating system it could occures damages on the computer.
5th Jul 2017, 6:10 AM
Jojo
+ 2
To delete a pointer, you have to allocate it dynamically. You need pointers on pointers... int **p; // this is a pointer on a pointer... If you delete a pointer you'll delete its value (adress of the variable pointed) but it won't affect the variable pointed.
5th Jul 2017, 3:48 PM
Jojo
+ 1
thanks jay and jojo. :)
5th Jul 2017, 2:52 PM
Krupesh Anadkat
Krupesh Anadkat - avatar
+ 1
just want to clarify, by deleting pointer we mean, the variable address stored inside pointer is erased . ?
5th Jul 2017, 2:55 PM
Krupesh Anadkat
Krupesh Anadkat - avatar
+ 1
got that, thanks @jay
5th Jul 2017, 4:24 PM
Krupesh Anadkat
Krupesh Anadkat - avatar
0
#include <iostream> using namespace std; int main() { int *p = new int; // request memory *p = 5; // store value cout << p <<endl<< *p << endl; delete p; // free up the memory cout << p <<endl<< *p << endl; return 0; } /*Output: address 1 5 address 1 (same as before) some big no. of type int (STRANGE) */
5th Jul 2017, 1:49 AM
Krupesh Anadkat
Krupesh Anadkat - avatar