Code::Blocks Forums
User forums => Using Code::Blocks => Topic started by: dr snuggles on July 27, 2007, 10:51:19 am
-
Is there a nice way to find memory leaks using Code::Blocks?
For example: See how much memory is allocated before and after running a certain function, to see how much memory the function needed. This might be useful in a function where you forget to delete a pointer. Maybe I'm stupid, but I couldn't find such memory leak detection in Code::Blocks :).
-
Hi !
Code::Blocks is an IDE. Its aim is not to detect memory leaks but edit code and call external tools, at least Compiler , Debugger and Linker to produce binaries.
It may be possible to integrate such a tool but Code::Blocks can't do itself.
Dje
-
Such things are tough... there are specialised tools for that purpose (for example valgrind), but they are not always easy to use/figure out or 100% reliable. You will have to expect false positives.
You can also use special allocators that count the allocations/deallocations. The BlockAllocator class used in Code::Blocks is an example for that (if compiled in trace mode).
Checking the amount of allocated/free memory before and after is not a working solution.
It is often better to avoid the problem alltogether by using "smart pointers" or "managed pointers", or whatever you want to call them, such as for example std::auto_ptr. It is only little more code, little or most of the time zero extra overhead, and it guarantees that your memory will be freed.
However, note that "smart pointers" may introduce ownership problems by themselves (which you must be aware of). Depending on what you do, you may need reference counted managed pointers, or not... be sure you read about the subject before shooting your foot.
-
So instead of hunting memory leaks, you advice me to use auto_ptr instead of normal pointers to avoid the problem. I should indeed do more research about auto pointers (I prefer not to use pointers at all to be honest).
Thanks for both of your replies :).
-
You have to be aware what that template (or similar templates) does, though. Smart pointers help a lot, but you have to use them wisely too, or they cause as many problems as they solve.
For example, std::auto_ptr transfers ownership if you assign it. In other words, it is not copyable. This means (among other things) that you cannot add it to a STL container, and that if you assign a = b; then b will be invalid, and accessing a member of b will cause a segfault (because a is now the only valid reference, and b is null).
Other smart/managed pointers have other properties, for example they may implement reference counting. This solves one problem, but introduces others...
Just make sure you understand the implications (you will need 1-2 afternoons of reading) before you use any of these classes/templates. Using the right smart pointer in the right situation guarantees that all will be well.