is there any way to clean up a memory leak without restarting your computer using a C++ Program?
Printable View
is there any way to clean up a memory leak without restarting your computer using a C++ Program?
>is there any way to clean up a memory leak without restarting your computer using a C++ Program?
Unless your operating system reclaims lost memory after the program terminates, the only solution is a reboot. You're better off removing all memory leaks from your program before running it.
>This scenario is pure speculation at best.
Very true. I don't know of any common operating systems that do not do this. My point of course was to mention that there is no need to reboot.
>Explicitly freeing memory before termination is completely a matter of style, and in some cases maintainability.
This I don't agree with. I've seen many cases where a good application is reused as a library and run continuously as opposed to just once. In those situations a memory leak will show itself because the system can't reclaim memory until after the program has terminated. The program running this broken library will eventually run out of free memory. So yes, explicit memory release is a matter of style, but also a hedge against disaster if the application is reused for other purposes. Wouldn't you agree that it's better to be pedantic and write good code from the start instead of waiting until your bad code becomes a liability?
i know fixing a memory leak before running the program is best, but i was wondering because sometimes i find a memory leak after running the program and i don't feel like restarting teh computer... idk... laziness==bad;
an example would be not setting the end link on a linked list to NULL...
>an example would be not setting the end link on a linked list to NULL...
That's not a memory leak, it's a dangling/uninitialized pointer. The typical result of not setting the end link on a linked list to null is an access violation when you try to dereference a pointer to memory that your program doesn't own. I'm assuming of course that you use something like this:
This will cause trouble if the last valid node's next pointer is not null.Code:for (it = head; it != 0; it = it->next)
{
// Do something
}
i'm sorry... i wasn't paying attention before... i meant when you run through the program without deleting the pointers... so the list is still in memory...
You might use something like this to manage chunks of memory.Code:
template <class T>
struct mmgr {
virtual mmgr(T * track = 0){ forget(), attach(track); }
virtual ~mmgr() { free(); }
T * attach(T * track){ free(); return memory = track; }
T * forget() { T * oval = memory; memory = 0; return oval; }
void free() { if(memory) delete[] memory; memory = 0; }
T * operator = (T * track){ return attach(track); }
T * memory; };
mmgr <int> mgr = new int[1000];
mgr = new int[500]; // o.k., 1000 ints freed.