If there is a tool like valgrind which allows to prevent memory leaks in a program, why the compiler doesn't use it and gives you the appropriate warnings? It would be too slow?


The compiler trusts the programmer. Some code might result in a memory leak depending on how you use it. Like malloc. If you look at the code, you would not know whether it results in a memory leak. It definitely can. Then fopen. Uses malloc and can create a memory leak. Where would you "detect" a memory leak if you're not examining the whole code of an executable? (also, I doubt it's possible at all)

And even valgrind, running an executable, cannot make sense of some code and will report false positives or false negatives (is it a memory leak if you allocate tons of memory but free it in a controlled out-of-memory shutdown?). And it will not catch memory leaks not appearing in that run.

Languages with garbage collection seem to evade the problem of lost pointers. A memory block without references is marked free. But even then you might accidentally hold a reference somewhere, and some implementations are more efficient but don't work for circular references (two objects referencing each other). And each garbage collection run usually will halt the system for a moment.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .