What do you do with a deleted pointer? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What do you do with a deleted pointer?

So I know about deleting pointers that were pointed at memory dynamically using the new operator, but what do you do with that deleted pointer? Use it for something else and continue re using it? Like what do programmers in the workforce use it for. Also, if I make a pointer, then point it at a new int, then delete it, does that hanging pointer take up memory itself? If so, what is the point of going through the whole process of using the new and delete operator besides not "having enough memory in the heap," or whichever form of memory you use when you create a variable?

2nd Jul 2018, 5:24 AM
Rain
Rain - avatar
2 Answers
+ 1
deleting pointers prevents memory leakage and frees up memory, as for whether a pointer with the same name can be reused, i'm pretty sure it can, but that can be tested pretty easily
2nd Jul 2018, 6:40 AM
hinanawi
hinanawi - avatar
0
Pointers are not deleted. Pointers are just variables to work with memory addresses and also act as a tool to access the heap segment addresses while allocating the memory to your program dynamically. Hence deleting a pointer as int a = 1; int *p = &a; delete p; leads to undefined behavior (or possibly program crashes when reaches to delete p; statement). When some storage cubbyholes of heap get claimed by new/malloc keywords as int *mem = new int; 0x0badbeef -> [garbage] mem would points to an address in the heap (e.g. 0x0badbeef), yet the content of that address is still garbage (e.g. -1379466288). After assigning a proper value indirectly as *mem = 10; 0x0badbeef -> [10] to that 4 bytes of heap, you can immediately restore the memory to the OS for other uses by deleting its content (NOT the whole int *mem) as delete mem; 0x0badbeef -> [garbage] you can reuse (reallocate) the mem further in the program as mem = new int; and delete its occupied data again as part of the recycling process.
2nd Jul 2018, 8:29 AM
To Seek Glory in Battle is Glorious
To Seek Glory in Battle is Glorious - avatar