0
explain the last line of output
deleting pointer from.heap meaning? https://code.sololearn.com/cLolR7k33Pe7/?ref=app
9 ответов
+ 8
as you have deleted the pointer p now points nowhere. The value it prints is random junk.
+ 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.
+ 6
** Just to clarify incase you didnt get notified of the edit.
delete p;
*p = nullptr;
+ 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.
+ 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.
+ 1
thanks jay and jojo.
:)
+ 1
just want to clarify,
by deleting pointer we mean, the variable address stored inside pointer is erased . ?
+ 1
got that, thanks @jay
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)
*/