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?
2 Réponses
+ 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
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.