+ 1

How to avoid memory Leak when Using pointers?

7th Apr 2018, 3:46 PM
RiGeL
RiGeL - avatar
4 Answers
+ 4
There are many pointer wrapper classes. 2 examples: There is a unique_ptr which deletes its underlying element in its deconstructor. unique_ptr is not slower than a raw pointer which is deleted by hand. There is also a shared_ptr. The underlying element of a shared_ptr is just deleted if no other shared_ptr points to it. But what if you must deal with old C code which uses raw pointers and something like ptr->free()? You creat a ptr_handle class which calls ptr->free() in its deconstructor. It's not slower and this way, you can be sure that ptr doesn't leak.
7th Apr 2018, 4:38 PM
Timon Paßlick
+ 2
Rahul thank you but can we also assign a NULL Value to the pointer after it has been deleted ? delete p; p=NULL
7th Apr 2018, 4:34 PM
RiGeL
RiGeL - avatar
+ 1
Martin Taylor thank you
7th Apr 2018, 4:32 PM
RiGeL
RiGeL - avatar
0
The memory that has been dynamically allocated for a certain purpose must be deallocated as soon as that purpose is over,in order to prevent memory leak.
20th Apr 2018, 2:44 PM
DEBAYAN BHAUMIK
DEBAYAN BHAUMIK - avatar