how memory leak.....

is there a way to delete a memory leak ?
like when the pointer is no longer pointing to that memory address, and that allocated memory is not accessible, how can i delete that ?

sample:
1
2
3
4
5
6
int *p = new int;
*p = 5;
//if i dont't delete p here, is that a way to deallocate the dynamically allocated variable above ? 
p = new int; //since p is no longer pointing to 5, and there's no way of accessing it
*p = 10
delete p; //i know this only deallocates the memory address which holds 10, not the one before 
It's not possible.
just delete p before you reallocate new memory space.
1
2
3
4
5
6
int *p = new int;
*p = 5;
delete p;
p = new int;
*p = 10
delete p;

When you detect them, it is a bug in your program. That is why it is called a memory leak, and why so many tools have been developed to find them so that they can be fixed. You need to stop the program, fix the leak, and rebuild the program. Then try again until there are no more leaks.
Or, you could avoid using new and delete altogether, and use standard containers and standard smart pointer wrapper classes instead.

If you write new in your code, it means it is possible to forget to write delete. Always try to remove that possibility by not writing new in the first place.
hmm...so i guess there's no way of deallocating them, anyway, was just wondering if there's a way of doing it, so i wont have to manually put delete it each time.
Topic archived. No new replies allowed.