Question:
C Program to detect memory leaks.?
Mohit Misra
2011-08-02 13:11:29 UTC
Looking forward to creating a c program to check for memory leaks...(of course in memory!!!).
Memory is said to be leaked if it has there is no available references to memory at that particular instant. So my initial idea is to check memory(bytes) to see if it is not referenced by any pointer. But the problem is...'how would I check it???'.

The program has been asked by one of my senior during his campus placements interview...and guess what...he couldn't answer that...but still got selected :P

Any ideas will be welcomed...:) Thanks in advance.
Three answers:
peteams
2011-08-02 14:08:38 UTC
In C you have no practical way of tracking pointer references.



You can do practical things in C++ that track references, however these are not normally used to find memory leaks. Moreover as these things often give you access to the underlying pointer they can be defeated in unexpected ways.



If you have all the scaffolding to detect when memory is unreferenced, you may as well just delete it. Languages like Java and C# manage their memory in this way.



Visual C++, and presumably other C compilers, do provide tools for debugging memory leaks. These work by allowing you to take a snapshot of what memory is allocated, run some code that supposedly allocates and deallocates memory and then check that no memory allocated after the snapshot is still allocated.



Without enforcing complete type safety in a language you cannot detect memory leaks. Consider the following C, does the memory get leaked and unleaked?



int n = (int)malloc(sizeof(int)) + 12345;

/* We have not pointer to the memory here, just an integer that has some relationship to the memory we allocated */

int* p = (int*)(n -12345);

free(p);
2016-12-01 15:45:07 UTC
No, "no longer able" potential "simply by way this device replaced into written". classes do no longer "lose" rules, badly written classes do. Badly written classes additionally fail to launch memory this is now no longer necessary. the main reason for memory leaks is the guy who write this device. (the sole way a properly written application ought to "lose" a pointer is thru hardware failure.)
angler
2011-08-02 13:29:27 UTC
probably not going to happen unless you rewrite your own malloc and calloc routines, that's why programs spend so much time in maintenance :P


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...