Stories
Slash Boxes
Comments

News for nerds, stuff that matters

Slashdot Log In

Log In

Create Account  |  Retrieve Password

Memory Checker Tools For C++?

Posted by kdawson on Wed Jun 06, 2007 04:40 AM
from the heaps-and-bounds dept.
An anonymous reader writes "These newfangled memory-managed languages like Java and C# leave an old C++ dev like me feeling like I am missing the love. Are there any good C++ tools out there that do really good memory validation and heap checking? I have used BoundsChecker but I was looking for something a little faster. For my problem I happen to need something that will work on Windows XP 64. It's a legacy app so I can't just use Boosts' uber nifty shared_ptr. Thanks for any ideas."
+ -
story
This discussion has been archived. No new comments can be posted.
The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More
Loading... please wait.
  • um (Score:5, Informative)

    by Anonymous Coward on Wednesday June 06 2007, @04:45AM (#19408479)
    boost::shared_ptr is not a memory checker, it's a reference-counted smart pointer, and works fine in legacy apps (such as compiled under VC++ 6).
    • Re: (Score:3, Informative)

      It's an alternative to needing a memory checker, though, so it would provide an valid solution to the problem for a new application.
    • Re:um (Score:4, Insightful)

      by Shadowlion (18254) <cdc@gis.net> on Wednesday June 06 2007, @07:23AM (#19409237) Homepage
      > and works fine in legacy apps

      Regarding legacy applications, I think the point was that he can't go back through the app and rewrite everything to use smart_ptr.
          • Re:um (Score:5, Insightful)

            by bhsurfer (539137) <bhsurfer@NOspaM.gmail.com> on Wednesday June 06 2007, @08:47AM (#19409931)
            The first thing I was told by my boss when I got hired was "You're going to look at this app and want to rewrite it from scratch. Don't do it, that's not what we want you for." Software doesn't need to be pretty, you just make improvements as you can and leave the ugly but solid code alone until necessary. It's an extremely rare situation to have the luxury of a complete redesign/rewrite.

            I guess that's a long way of saying "I agree completely with what you just said."

              • Re:um (Score:4, Insightful)

                by bhsurfer (539137) <bhsurfer@NOspaM.gmail.com> on Wednesday June 06 2007, @10:42AM (#19411551)
                I meant "ugly" in the sense of "Not the way I would have done it" rather than in a "Holy shit, what a freakin' mess! This guy should be bagging groceries, not writing software!" kind of way. I certainly do not think that clever tricks and mounds of complex spaghetti code that were designed by avalanche is maintainable, believe me.

                I also have (unfortunately) written enough ugly stuff that when I go back later I say "I can't believe I actually did something that stupid."

                You live, ideally you learn, and when you look at code you wrote 5 years ago you likely slap your forehead in embarrassment - that's how you know you're getting better. That, and when your coworkers aren't trying to slash their wrists when they get handed something you wrote...

              • Re:um (Score:5, Insightful)

                by joto (134244) on Wednesday June 06 2007, @10:44AM (#19411587)

                If its ugly its not solid. Ugly code is hard to understand at first glance, and its easy to introduce an error. Or do you consider code that's easy to make a mistake with as actually being "maintainable"?

                You are confusing two aspects here. Ugliness does limit maintainability. But it does not limit "solidness". "Solidness" would mean that the code actually works, and has a proven track record, such as being used in production for over 20 years. Code that has been in production for over 20 years is usually both solid and ugly.

                That ugly code is usually a monument to the "there's not enough time to do it right, but there's always enough time to do it over ... and over ... and over" and "ship it now - fix it later."

                Or it could be a monument over "the world is a complex place, and if you change anything here, and it causes the program to fail in some weird special case, your company is going to loose umpteen zillion dollars". While the reality is probably somewhere in between, rewrites should still be avoided like the plague. However, if you really have taken the time to understand what some nasty bit of code does, there's nothing wrong about cleaning it up. But most of the time, the ugly code is there for a reason.

  • two points (Score:4, Interesting)

    by sentientbrendan (316150) on Wednesday June 06 2007, @04:49AM (#19408497)
    This isn't really an answer to your question, but it's on topic and there's some questions I wanted to get answered myself.

    First of all, shared_ptr is going into the standard library as part of TR1. Does anyone know when common development environments, i.e. GCC and MSVC, will start including TR1?

    Second, I believe that there are a number of garbage collectors available as libraries for C++. I've heard boehm's garbage collector mentioned numerous times. My question is, are any of these libraries any good? Are they really practical to use in real world applications? Do you have to modify all of your types to use it, or can primitive and stl types work with it?
    • Re:two points (Score:5, Informative)

      by Anonymous Coward on Wednesday June 06 2007, @04:52AM (#19408509)
      Boehm's garbage collector is used in Inkscape -- and they did gradually introduce its use, so you can start using it for some things and gradually extend the usage.

      Boudewijn
    • Re:two points (Score:4, Informative)

      by Anonymous Coward on Wednesday June 06 2007, @05:02AM (#19408567)
      gcc 4.2 includes a good part of tr1 as was released (late) a few weeks ago.

      shared_ptr is a blessing and a curse. It saves you from manually destructing objects held in a collecton (good) but too many developers use it for lifetime management (bad).

      • Re:two points (Score:4, Interesting)

        by shutdown -p now (807394) <(int19h) (at) (gmail.com)> on Wednesday June 06 2007, @07:28AM (#19409263)

        too many developers use it for lifetime management (bad).
        Why is it bad? Isn't the whole point of shared_ptr to automatically manage the lifetime of a shared resource?
        • Re:two points (Score:5, Insightful)

          by Anonymous Brave Guy (457657) on Wednesday June 06 2007, @12:15PM (#19413093)

          It's not automatically bad, but using semi-automated memory management like this tends to reduce the emphasis on constructing things only when they're needed and destroying them immediately when you're done with them. This concern, known as "Java bloat syndrome" in honour of the language that first popularised it, can lead to major performance problems in applications that manipulate a lot of data, and is a favourite mistake made by the cult of "hardware is cheap, so optimisation doesn't matter".

          The thing is, this sort of care-free programming philosophy is natural in languages like Java, so languages like Java have had to learn from their early mistakes and adapt. There have been dramatic improvements in GC technology since those early days, and today there isn't the same degree of performance penalty associated with relying on GC to clear everything up.

          However, this sort of behind-the-scenes magic isn't really the "C++ way". You can do it, but tools like shared_ptr don't have the same level of sophistication as full-blown GC. Using them requires some care from programmers, and as the grandparent post said, this can lead to problems if the programmers come to rely on them more than they ought.

          FWIW, I'm not sure I'd have described things in quite such black-and-white terms as the GP, but I can see the underlying point and I think it's a valid one.

          • Re:two points (Score:4, Insightful)

            by shutdown -p now (807394) <(int19h) (at) (gmail.com)> on Thursday June 07 2007, @12:45AM (#19420617)
            In other words, programmers shouldn't use shared_ptr as if it were a replacement for GC. When it is worded thus, I can fully agree with that (and indeed, anyone who understands how reference counting works, will agree as well). The nice thing about shared_ptr is that, unlike GC, it is still fully deterministic, and so it properly preserves the "C++ spirit".
      • Re:two points (Score:5, Informative)

        by d00ber (707098) on Wednesday June 06 2007, @08:48AM (#19409943) Journal
        Also, shared_ptr has been promoted to the draft standard C++-0x so you can use std::shared_ptr.

        You'll be able to use C++-0x in gcc-4.3 with a switch.

        I also heard that std::auto_ptr is being deprecated (not removed) I guess in favor of rvalue references.

        Finally, there [open-std.org] is a motion to include garbage collection in the C++ language. This is sponsored by none other than Hans Boehm among others.

        I realize this doesn't help immediately.
          • Re:two points (Score:4, Informative)

            by d00ber (707098) on Wednesday June 06 2007, @11:49AM (#19412697) Journal
            My understanding is that it will be opt-in. I think manual management will be the default.

            They don't want to remove the old ways (including malloc/free). And they don't want to penalize people who don't use garbage collection. In other words, if you don't want to use garbage collection you won't be paying for it in code size/runtime.

            But for them that do... It might be nice to offer it.

    • Re: (Score:3, Informative)

      Boehm's gc is very very good...on par with Java's collector and others. The source needs cleaning up, and some configuration bugs to be ironed out, but it is very good.

      In order to use it, you just have to include 'gc.h' in your files, which replaces 'new' with 'gcnew' using macros. Alternatively, you can bypass the standard library and provide a replacement for 'malloc' and 'free', but I did not manage to do that (due to the configuration bugs mentioned above).
    • Re:two points (Score:4, Interesting)

      by Craig Ringer (302899) on Wednesday June 06 2007, @08:07AM (#19409549) Homepage Journal
      gcc has included most of tr1, especially <tr1/memory>, since at least 4.1. I think it was in 4.0 as well.

      It's a pity there's no way to ensure compatibility between boost::shared_ptr and std::tr1::shared_ptr , nor a really attractive non-preprocessor-reliant mechanism to switch between them (since typedefs in C++ do not work on incomplete template types).

  • by Rezonant (775417) on Wednesday June 06 2007, @04:51AM (#19408505)
    Yep, Paul Nettle's little memory manager rocks. It WILL find leaks in your program. http://www.paulnettle.com/ [paulnettle.com] (Yes, you have to navigate through a horrible flash site to get it, but it's worth it).
      • Re: (Score:3, Informative)

        It's true that MMGR is single thread only, and if your program allocates and frees memory on multiple threads you should choose another alternative. However, many many programs only allocate and free memory on one thread, and for those MMGR is simple to use and is pretty damn good at finding leaks, overruns and similar problems.
  • STLPort (Score:4, Informative)

    by kazade84 (1078337) on Wednesday June 06 2007, @04:58AM (#19408541)
    I know this isn't exactly what the article is looking for. But, if you are using the STL (which you SHOULD be!) you may be interested to know that the STLPort [stlport.org] STL implementation includes a debug mode which contains loads of error checking to make sure you aren't misusing STL.
        • Re:STLPort (Score:5, Informative)

          by Chris_Jefferson (581445) on Wednesday June 06 2007, @06:02AM (#19408863) Homepage
          Actually, yes they do. In g++ use " -D_GLIBCXX_DEBUG ", in VC++ enable debugging. You'll get all these errors and more. I don't understand why everyone seems to know this part of stlport and don't realise other librarys have it as well.
  • by DrXym (126579) on Wednesday June 06 2007, @04:59AM (#19408549)
    I've played with Boundschecker, Purify (& Quantify) and Fortify. My experience of these tools is that they either take a painfully long time to run, throw up too many spurious warnings or crash outright after eating all available memory / disk space.

    They might be useful for small apps but if you have a massive app they are almost more trouble than they are worth.

    It's hard to say what you can do except foster safe coding practice and highlight the common pitfalls such as memory leaks, buffer overflows etc. Many compilers can help detect heap / memory overruns because the debug libs put guard bytes on the stack & heap that trigger exceptions when something bad happens. There are also 3rd party libs such as Boehm [hp.com] which help with memory leeak / garbage collection issues and dump stats. I'd say using STL & Boost is also a very good way of minimizing errors too simply because doing so avoids having to write your own implementations of arrays, strings etc. which are bound to be less stable.

    • Re: (Score:3, Interesting)

      They might be useful for small apps but if you have a massive app they are almost more trouble than they are worth.
      I'm of the opinion that the larger the application, the harder it is to write. So my philosophy is to chop programs up in different processes. The fact that you're stating that the memory checkers are only useful for small apps, might be a sign that your app is too big.
    • by Anonymous Coward on Wednesday June 06 2007, @07:51AM (#19409417)
      Most people can't understand Purify's output, and I've actually ran across coders who actually believe their code can't be as bad a Purify says it is.

      For example, this code has serious issues:

      extern string method_that_returns_string_object();
      char *ptr;
            .
            .
            .
      ptr = method_that_returns_string_object();
            .
            . .
      That actually will compile, and seem to "work". But it's horribly wrong, and Purify will find the problems.

      And FWIW, I've used Purify on massive apps, and found huge problems that the developers didn't even know were there. On one project, they couldn't explain why their "perfect" app kept crashing, either. Worse for them, I had been hired as a consultant to fix their problems that they couldn't seem believe existed (HINT: your boss hired someone from the outside...), and after watching the team flail and spend literally almost a man-year trying to find one memory bug, I finally had enough of "advice giving" being ignored and got on their system, linked their app under Purify, ran it, and found the bug - a double delete of an object from two different threads. It all took me about fifteen minutes. I did that in front of their management. I made my point.

      Purify (and like tools) are a great help. Not using them is like trying to build a house without power tools. Yeah, it can be done. But what would you think if hired a builder to make your house and his team showed up carrying hand saws? Oh, and you are paying that team to hand-saw all the lumber...

      What would you think of that builder?

      Yet, when a developer asks for tools like Purify, management often balks. Because 1) they're shortsighted, and 2) developers don't know how to use such tools.

      Like I said - what would you think of a construction company where the workers don't know how to use modern power tools to help their productivity?

      Well, you just put yourself in that category.

      Yes, Purify is somewhat slower than running without Purify. But it's a lot faster than most other full-memory checking methods. If you're worried about speed, link against the Win32 debug libraries - they'll at least show problems with double free() calls, access of free()'d and deleted objects, etc. And without too much performance problems.
      • Re: (Score:3, Insightful)

        I love this comment, from Bjarne Stroustrup's home page (href=http://www.research.att.com/~bs/bs_faq2.htm l #memory-leaks [att.com])

        Q) How do I deal with memory leaks?

        A) By writing code that doesn't have any. (goes on to advocate vector & string)

        And also: C++ Is my favorite garbage collected language because it generates so little garbage (http://www.research.att.com/~bs/bs_faq.html#reall y-say-that [att.com])

        Over the past 6 months or so, I've really made an effort to better my usage of C++ (using Effective C++, Effective
          • by peterpi (585134) on Wednesday June 06 2007, @09:12AM (#19410277)
            I didn't explain it all that well. What I mean is; I love destructors.

            A good example of what I'm talking about is a std::ifstream versus a java.io.FileInputStream. If you make an ifstream on the stack, you can be absolutely certain that when it goes out of scope, the destructor will be called and the file closed. You can be certain that it will happen, and you can also be certain when it happens; at the very point it goes out of scope.

            With a heap based FileInputStream, you have no such gaurentee. You leak it, and you just hope that the finaliser gets called soon (if at all). I've had more than one occasion where I've been leaking FileInputStreams quicker than the garbage collector cares to clean them up, and sooner or later the OS says 'no' and you get an exception. And it's very difficult to reproduce, because it's all down to the whim of the garbage collector, and you always go slower when you're looking for a bug.

            Of course the answer to this is to say "Well you should Close() your input stream beforehand". But that's just as bad as saying "You should delete your heap based objects" in C++. It's that situation of having to manually shut down objects that seems old fashioned to me.

            Maybe there's a better way these days, I've been away from Java for a couple of years now.

            (I do enjoy coding in either language though!)
  • Boost? Ugh (Score:3, Interesting)

    by Viol8 (599362) on Wednesday June 06 2007, @05:01AM (#19408559)
    Talk about a sledgehammer to crack a nut. Boost strikes me as the sort of library used by people who want to show off how up to date their skills are , not people who really need to write a program to get a job done. Its bloated , has a wierd syntax that differs from the C++ norm and doesn't solve any problem that isn't already solved or could be done quite easily by standard C++ anyway. What is its point except as intellectual masturbation by its authors? No this isn't a Troll, this is a post by someone who was forced to use Boost for a year and I loath it. Yeah , mod me down , whatever...
    • Re:Boost? Ugh (Score:5, Interesting)

      by pzs (857406) on Wednesday June 06 2007, @05:10AM (#19408603)
      I would be inclined to agree with this. I used the Boost Graph Library for some research code a few years ago. It's been designed to be extremely generic, which although a good thing sometimes makes it pretty difficult to just start coding something without all the bells and whistles. For operations on graphs, such as walking through, you can use their specialised functions for doing things but it takes days and days to work out how to use them and I ended up just using regular loops because they were much easier to understand.

      Getting it to compile was a bit of a nightmare too. It has its own native compilation management tool that you have to download as well. What the hell is wrong with using make like everybody else? It also uses a very complex template hierarchy that produces terrifying error messages.

      I'm sure that once you become an expert, BGL is really powerful and efficient, but I found the learning curve too steep. I just want to get in and build a working prototype quickly so I can see what I'm doing, not spend hours wading through manuals and examples to build the simplest program.

      I'll be with the parent post and get modded a troll by boost developers.

      Peter
      • Re: (Score:3, Informative)

        You don't usually need to build anything to use BGL - it's mostly header-only library. It has only two small helper files.

        And Boost.Build is muuuuuch more powerful than makefiles. You can try to use Boost.Build v2 in your own projects - it's very very useful.
      • Re:Boost? Ugh (Score:5, Insightful)

        by Viol8 (599362) on Wednesday June 06 2007, @05:28AM (#19408693)
        "you'd better get used to the "weird syntax" of templates and especially the boost libraries"

        I'm used to templates syntax (though I think its ugly and Stroustrup could have done a lot better) but Boost makes it worse by overloading operators and then using them in ways never intended that produce syntax that a plain C++ wouldn't even recognise, never mind understand what its doing.eg the gratiutous overload of () for matrix ops where a simple function call would have been much cleaner and easier to follow.
                • "I suppose you like adding vector components manually, instead of doing v1 + v2?"

                  No , something like vectorAdd(v1,v2) would be a lot more readable and a damn site easier to grep for. Idiot.

                  Then probably we should remove the operators for built-in types as well. After all, you could use functions like doubleAdd(a, b). As a bonus, you'd not get nasty surprises when mixing unsigned and signed integers. intGreater(a, n) would always give you the expected answer, even if a is negative and n is unsigned. If you'd want to compare in unsigned arithmetics, you'd use uintGreater(a, b) instead. And what dereferenePointer(p) does is self-evident, unlike *p. Also, removing all operators would greatly sim

  • by Photo_Nut (676334) on Wednesday June 06 2007, @05:04AM (#19408581)
    PageHeap is a debugging tool for Windows created by Microsoft. It does what you want.

    For more information look here:
    http://support.microsoft.com/kb/286470 [microsoft.com]
  • Valgrind (Score:5, Informative)

    by bms20 (827647) on Wednesday June 06 2007, @05:06AM (#19408593)
    Use valgrind : www.valgrind.org It is (in my opinion) the best tool available for this purpose. In fact, I develop C++ exclusively on linux first because of valgrind, then port to Win32 later. By the way, you're not missing out on anything special by not programming in Java or C#. Both of those languages are slow, and introduce their own language complexities. -bms20
    • Re: (Score:3, Informative)

      If you still think Java/C# are slow, especially in terms of memory management you might want to read this:
      http://www.ibm.com/developerworks/java/library/j-j tp09275.html [ibm.com]
        • Re: (Score:3, Interesting)

          Another link you might like to read (just done some search on google):
          http://www.idiom.com/~zilla/Computer/javaCbenchmar k.html [idiom.com]

          Of course you can create your own "dynamic" allocator in C++... but that doesn't make allocation/deallocation automatically faster.

          Maybe you should search for some numbers to support your argument... just by stating "I don't buy it, C++ is still faster" it doesn't become reality.
    • Re: (Score:3, Interesting)

      By the way, you're not missing out on anything special by not programming in Java or C#. Both of those languages are slow, and introduce their own language complexities. -bms20

      Speed isn't everything. If your server application is network or database bound then stability and API richness is considerably more important than speed of execution. After all, does it matter that your app completes 2ms faster if it has to wait 500ms for the database to return? Or that it crashes more frequently? Or that you can't

    • Valgrind's default memcheck tool is an excellent way of finding memory errors - ranging from extremely subtle to obvious. In addition, Valgrind can be used as a code profiler, cache simulator and many other things. It really is an excellent tool - I recommend it to anybody writing C++.
    • Re: (Score:3, Informative)

      Use valgrind : www.valgrind.org It is (in my opinion) the best tool available for this purpose. In fact, I develop C++ exclusively on linux first because of valgrind, then port to Win32 later.

      It's been a few years since I last programmed in C++, but Valgrind indeed really saved the day on a regular basis. Also look into (KDE-)frontends if you think looking at text output is not very convenient. Couldn't agree more with this part, it's the best tool I've seen - and it's free software, too.

      By the way, you're

    • Re:Valgrind (Score:4, Informative)

      by Rogerborg (306625) on Wednesday June 06 2007, @09:00AM (#19410127) Homepage
      Agreed. I am not a fan of Linux development environments, but there really is nothing like Valgrind available for Windows, so run as much of your code as possible through Valgrind on Linux. I'd say that it is worth the effort, even if you have no intention of supporting a Linux distribution.
  • eFence (Score:4, Interesting)

    by cannonfodda (557893) on Wednesday June 06 2007, @05:12AM (#19408613)
    I haven't used it for a while, but I used to use Bruce Peren's efence [perens.com] for bits of malloc debugging, it hasn't been actively developed for ages but it's pretty light weight if that's what you need. There appears to be an up to date branch DUMA [sourceforge.net] which I haven't tried. As far as I remember you can use efence under WIN and DUMA claims to work......

    Unfortunately, what you prolly want is valgrind or purify.
  • Visual Leak Detector (Score:3, Interesting)

    by Tucano (1112131) on Wednesday June 06 2007, @05:34AM (#19408721)
    I have tried mainly Boundschecker and Purify, and they were usually quite slow and difficult to set up and produced lots of spurious results. Also, quite often they simply didn't work at all and refused to run certain programs. A few years ago I reduced the problem to a 10 line C++ program that would crash Boundschecker or Purify, can't remember anymore which one it was.

    In any case, Visual Leak Detector is a free memory checking tool. It's only for Windows / Visual Studio, but if you are using that, VLD is awesome: http://www.codeproject.com/tools/visualleakdetecto r.asp [codeproject.com]

    It's super easy to set up, just #include "vld.h" somewhere in your program, and then run the debug mode. No need to rebuild everything in instrumented mode, and no false results (at least I haven't got any). Real memory leaks will be reported in the output window of the IDE.
  • by Tronster (25566) on Wednesday June 06 2007, @07:07AM (#19409149) Homepage
    Last week on Gamasutra was a good article on memory leak detection, and how to role your own tool:

    "Monitoring Your PC's Memory Usage For Game Development" [gamasutra.com]

    While the title says it's for game development, I found that the meat of the article applies to any windows developer.
  • by seniorcoder (586717) on Wednesday June 06 2007, @08:19AM (#19409653)
    We are running many high speed financial message processing applications. A crash for any reason (including a leak) would be very costly for us.

    We pre-allocate pools of objects at startup and then re-use them. No other memory is allocated or freed while the process is running. Our pools of reusable objects are monitored very carefully as an object that isn't release back to its pool when the job is done is akin to a memory leak. Use of sentries to automatically release objects back to the pools when they fall out of scope is mandatory.

    So my answer is to the problem is:
    1. Use sentries (or some other mechanism) to guarantee memory is released.
    2. Don't allocate except at startup.
    3. No need for elaborate tools due to the above.

    I'm sure that not all applications data usage would fit into this model, but it is surprising how many can.

    We have seen some leaks in our applications. These were tracked down to STL internally leaking. They weren't generally very large and therefore we continue to live with them.

    On the subject of garbage collectors, some of our colleagues use Java and .NET. Both sets of colleagues have had major performance problems caused directly by the garbage collectors kicking in and consuming vast CPU power while they did their thing. The result was a failure to process messages in a timely manner in our high speed environment. The solution in both languages was to use pools of reusable objects and never cause their reference counts to drop to 0. Thus they implemented the very same mechanism that we use in C++ and avoided the garbage collectors.

    So don't think that a garbage collector is the solution. Perhaps in less demanding applications it is a potential answer.

    Lastly, I strongly dislike anything from Rational. I find them overpriced unreliable bloatware (YMMV). Purify used to be good some time ago, but those days are long gone.

    I echo what others have said above. You are a developer. You know your requirements. Build a simple tool to monitor and check your usage. For us it was managed pools of re-usable objects.
  • Memory Validator (Score:4, Informative)

    by sdt (7606) on Wednesday June 06 2007, @08:30AM (#19409755) Homepage
    Have a look at memory validator [softwareverify.com]. I don't know if it supports 64 bit applications, but it has a great list of features [softwareverify.com] and is the only decent memory validation tool I've ever seen on Windows.
  • by Heir Of The Mess (939658) on Wednesday June 06 2007, @09:17AM (#19410327) Homepage
    Use a testing framework like Parasoft's CPP stuff http://www.parasoft.com/jsp/products/home.jsp?prod uct=CppTest [parasoft.com]
  • by cant_get_a_good_nick (172131) on Wednesday June 06 2007, @11:11AM (#19412079)
    GLIBC allows you to create hooks for the standard mem functions (malloc/realloc/free). Remember that g++ still calls these under new/delete so it works for C++ also.

    One of our guys coded up a simple shared lib that can be loaded with LD_PRELOAD that sets simple hooks of printing memory locations for new/realloc/delete. He then wrote a perl script that kept track of these things and spit out anything that was malloc'ed and not realloc'ed or free'd.

    I can't post it, because technically it's not my code it's my company's. But his shared lib code is just 300 lines long, and shouldn't be hard to duplicate. The perl log filter is even more straighforward. Each malloc gets saved. Each free removes the malloc. Each realloc removes the old malloc and adds a new one. Anything left over is a leak.

    Override __malloc_initialize_hook with a pointer to your init_function. In your init_function, save the old functions at __malloc_hook __free_hook __memalign_hook and __realloc_hook and substitute your own. Now write your replacement functions, in it, do your logging and temporarily replce the old hooks and call the original functions, replace with your hook on the way out to get the next call. All of the hooks should be wrapped in a mutex to help re-entrancy problems.

    It's not a full memory detector, just does leaks, but it's non-intrusive, requires no recompiles, and is the best way we have to leak detect our huge server long running code.
    • Re:Duh! (Score:5, Funny)

      by WrongSizeGlass (838941) on Wednesday June 06 2007, @05:17AM (#19408641) Homepage

      Replace new/delete, malloc/free, whatever/whichever, with your own tracking version. In the end you may come out with an even better idea of memory handling for whatever you are working on at the time. God-awful simple you idiot !! You disgust me that you are so stupid !!
      Just replace that post with your own comment system, such as replacing God-awful with I'm, idiot with smart, disgust with inspire and stupid with curious.
    • Re:I've used... (Score:5, Informative)

      by TapeCutter (624760) on Wednesday June 06 2007, @05:52AM (#19408805) Journal
      If you use MS compilers the memory debug stuff is in crtdbg.h, IIRC it has been there in one form or another since V1.5 but for some reason seems too obscure for the average Windows programmer to find. ;)

      It is a very handy feature for finding leaks, buffer overflows, ect. The only other product I've used to find memory problems on recent incarnations of Windows is Purify. The MS solution is infinitely simpler because it's built into the environment and it's narrowly focused on memory problems. To state the obvious and in fairness to Purify, MSDev is infuriatingly fussy when it comes to building debug modules for IBM's Purify.
    • by Anonymous Coward
      I used to select tools for my team. For UNIX, I selected Purify and for Windows, BoundsChecker. After a few days with BoundsSlacker, **all** and I mean every one of my team was asking for Purify for Windows licenses. 17 licenses later and our code crashes have dropped byat least 90%.

      Yes, it isn't cheap. Just do it. You'll thank me.

      The productivity increase alone will make it worthwhile for management.
    • Re: (Score:3, Interesting)

      Yeah, I haven't used Purify in a few years, but when I tried it out it seemed very effective and found some bugs that would have been hard to track down otherwise. We didn't use it in the end because, at least at that time, it didn't like us dynamically generating machine code... otherwise it was better than anything else we tried; for normal C and C++ code it should work well.