Wipro Technologies Interview Question
Technical ArchitectsCountry: India
There are various approaches you can take but before you embark on the journey, you need to make sure that there's a memory leak to begin with.
Once you are sure, you could use tools like leakdiag or IBM purify to see the stack trace of possible leaks (this is not guaranteed though). You may find the area of leak or may not. But Idea is to narrow down the scope. Once you have where the memory leak is.
Now, you need to jump and see what exactly you aren't freeing (this step is different depending on code base) Wrapping your resources around shared_ptr might be a good way to avoid memory leaks. Solving memory leaks are arduous and painful to the least. try to avoid it by all means.
For dynamic memory leaks:
- Laxmi Narsimha Rao Oruganti November 16, 2011In C++:
We can override new, delete operators. We should also make sure to override new[] and delete[] operators. The override methods, internally call C++ built-in routines, plus do tracking. By tracking I mean:
- On new (and new][]), we add the memory pointer (if not null) to a hash table
- On delete (and delete[]), we remove the entry in hash table.
When the program terminates, one can check the hash table contents. If the hash table is empty, then there are no leaks. Otherwise, there are leaks. We can also check double-free/double-deletes in this override model. When someone deletes a pointer, and the entry does not exist in hash table; it means it is either a random address are double-free.
Similarly, in C:
We can write our own malloc and free functions Ex: mymalloc and myfree. These routines are same as the routines mentioned above. The only catch is that we have to expect every allocation to use these my* methods than built-in methods. If your C compiler supports function/method overrides, you could override malloc and free as well.
For static memory leaks:
I am assuming you meant to say 'unused' variables. By unused, they are either not initialized or initialized but never used (never participated as R-Value, OR, always appeared as L-Value). This is done using code parsers. Here we have to write C language parser much like compiler. And do a static analysis of code.
Thanks,
Laxmi