Summary: How to detect memory leaks better? 
Author Message
 Summary: How to detect memory leaks better?

(From threads:
      Memory leak related to the std::string?
      Memory leak?
)

Hi,

Firstly, thanks to those who answered my question. Secondly, I
am going to summarize the question and answers to that
question and also to similar ones from other threads (a
contribution to the "memory leak week" :). Some
questions (of mine) still remain...

My original question asked why the memory leak is detected
in the following code... (Microsoft VC++6 Ent.)

Quote:

> #include <crtdbg.h>
> #include <stdio.h>
> #include <string>

> int main(int argc, char * argv[])
> {
>     std::string s("Hallo world!\n");
>     printf("%s", s.c_str());
>     _CrtDumpMemoryLeaks();
>     return 0;
> }

Markus Sch?pflin explained...

Quote:

> This is no leak. When you reate an object of class string, it
> allocates memory for the characters. The memory is deleted
> when the object goes out of scope. In your case, the scope is
> the main function, hence the object is deleted when leaving
> the main function.

> By the way, you almost certainly don't want to use
> _CrtDumpMemoryLeaks() directly, as in the end, it simply dumps
> all memory that is currently allocated. Instead, look up
> _CrtSetDbgFlag() or use _CrtMemCheckpoint() and
> _CrtMemDumpAllObjectsSince().

which also explain why I did observe "Detected memory leaks!"
blocks with the content stored only in static const
std::string variables (class constant member variables in my
case).

John Keenan added...

Quote:

> Therefore the following should not show any memory leaks:
[...]
> int main(int argc, char * argv[])
> {
>     {
>         std::string s("Hallo world!\n");
>         printf("%s", s.c_str());
>     }
>     _CrtDumpMemoryLeaks();
>     return 0;
> }

[...]

Then, Chandler Gellar proposed...

Quote:

> I have found that the following is the best way to set up leak
> detection in a non-MFC app..

> 1) Your pre-compiled header file should contain this at the top:

>  #define _CRTDBG_MAP_ALLOC
>  #include <malloc.h>
>  #include <stdlib.h>
>  #include <crtdbg.h>

> 2) The first line of your "main" function should always read:

> _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

> Leaks will be dumped automatically on program termination --
> no need to call _CrtDumpMemoryLeaks().

As I do write the application with windows (the simple console
application was used just to show the problem) ane I use ATL
(which includes crtdbg.h, etc.), I've only added the following
line to the WinMain():

  _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

Some blocks of the memory-leak blocks disappeared (like those
related to the static const std::string variables) and some
remained -- they probably are the real memory leaks (errors
between my chair and my keyboard :)

Pieter Op de Beeck asked in the thread "Memory leak?"

Quote:

[...]
> #include <iostream>
> #include <crtdbg.h>

> void main ()
> {
>         _CrtDumpMemoryLeaks();
> };

> giving me memory leaks [...]

Doug Harrison (Visual C++ MVP) redirected my attention to
the mentioned thread where he explained:

Quote:

> <iostream> or the (draft) Standard C++ RTL define some
> global objects that allocate memory, while
> <iostream.h> doesn't, and you're dumping leaks before
> those globals are destroyed. Consequently, you get
> spurious leaks, and you're making exactly the same
> mistake MFC does. Let the CRT report leaks after it's
> destroyed static duration objects and run atexit()
> functions, which is the only right time to report
> leaks outside of regions bounded by
> _CrtMemCheckpoint(). Assuming you're using the MS CRT,
> I can't think of a single reason to call
> _CrtDumpMemoryLeaks().

[Notice the last sentence!]

- Show quoted text -

Quote:
> You should use the checkpoint functions and other functions
> that deal with _CrtMemState.

> NB: To cause the CRT to automatically dump leaks at exit, you
> will need to use _CrtSetDbgFlag and _CrtSetReportMode, e.g.

> // Compile with cl -MDd -ZI b.cpp

> #include <crtdbg.h>

> void main()
> {
>    _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)
>       | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_ALLOC_MEM_DF
>       | _CRTDBG_CHECK_ALWAYS_DF);

>    _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
>    _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
>    _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
>    _CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
>    _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
>    _CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );

>    new int[10];
> }

BTW, one should not use "void main()" (int would be better).

Quote:
> If you #include <iostream>, ...

[this was the difference which made the Pieter's code output the
message about memory leak detection]

Quote:
> ... you'll find that it doesn't increase the leak count. Also
> note that leaks reported at program exit may not be important,
> because there's little point in freeing memory that was
> dynamically allocated but needs to exist throughout the
> program's execution. Freeing this memory may slow program exit
> due to paging effects.

If I use the dynamic allocation a lot in my application, does
the last notice mean that I should always use mem-state and
checkpoint functions? Or can I distinguish that "little point
in freeing memory" case from the real (my own fault) memory
leaks?

Thanks,

Petr

--
Petr Prikryl, SKIL s.r.o.,  e-mail: prikrylp at skil dot cz
                            Please, don't reply via e-mail.



Mon, 28 Oct 2002 03:00:00 GMT  
 Summary: How to detect memory leaks better?
Thanks for the summary.....nice to see that someone knows how to use a
newsgroup properly


Mon, 28 Oct 2002 03:00:00 GMT  
 Summary: How to detect memory leaks better?

Quote:
> Then, Chandler Gellar proposed...

> > .....
> > Leaks will be dumped automatically on program termination --
> > no need to call _CrtDumpMemoryLeaks().

> As I do write the application with windows (the simple console
> application was used just to show the problem) ane I use ATL
> (which includes crtdbg.h, etc.), I've only added the following
> line to the WinMain():

>   _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

> Some blocks of the memory-leak blocks disappeared (like those
> related to the static const std::string variables) and some
> remained -- they probably are the real memory leaks (errors
> between my chair and my keyboard :)

    Yes, take a look at the memory leaks that remain. Each leak that is
reported will include an "allocation number." Set a breakpoint at the given
allocation number. When the breakpoint is hit, look at the call stack debug
window and you'll see the exact line of source code that is calling the
'new' that is never 'delete'd... Your investigation  SHOULD lead you to a
point in your own source code. This approach seems to work for me.
    If you need help with setting breakpoints at an allocation number, post
another message.


Mon, 28 Oct 2002 03:00:00 GMT  
 Summary: How to detect memory leaks better?


Fri, 19 Jun 1992 00:00:00 GMT  
 Summary: How to detect memory leaks better?


Quote:
> If I use the dynamic allocation a lot in my application, does
> the last notice mean that I should always use mem-state and
> checkpoint functions? Or can I distinguish that "little point
> in freeing memory" case from the real (my own fault) memory
> leaks?

Quite apart from the question of how to detect such
situations, and how to distinguish them, is the issue
are there really situations where you don't care
about leaked resources?

In some cases, it is often the practice of coders to
leave things that "fall off the end" of a program.
When main hits its closing brace, sometimes some
coders will not mind if some things have not been
explicitly freed up.  They won't bother to run around
and make sure every resource has a destructor or an
explicit free-it-up call.

The thing about this is, it can only be said to be ok
in the context of the specific program at hand.  If
the code you have written ever gets borrowed, by you
or by others, and winds up in some other context,
you may find that the Vorlons have contacted the
Foul Marmidons, and all is chaos.  For example, if
you write some code that gets included in a library,
and it leaks, then folks will be upset with you.

So, if you have any possibility that your code will
get reused, you should do your best to make it completely
leak free.  And that includes memory, file handles,
screen resources like window handles, thread handles,
and any other resource that can leak and be exhausted.
If you are *certain* the code will never get copied
to another project, and the project's nature will never
change so the leak matters, then feel free to write it as
sloppily as you like.  I'm thinking this might include
some code snippet you used to see if your compiler
accepts a particular syntax.  But not much beyond that.

--
Dan Evens
Standard disclaimers etc. No spam please.



Mon, 28 Oct 2002 03:00:00 GMT  
 Summary: How to detect memory leaks better?


Fri, 19 Jun 1992 00:00:00 GMT  
 Summary: How to detect memory leaks better?

Quote:

> If you need help with setting breakpoints at an allocation number, post
> another message.

I would appreciate some details on how to do this.


Mon, 28 Oct 2002 03:00:00 GMT  
 Summary: How to detect memory leaks better?
Look up CrtSetBreakAlloc() in the online help

Joe

Quote:

> > If you need help with setting breakpoints at an allocation number, post
> > another message.

> I would appreciate some details on how to do this.



Mon, 28 Oct 2002 03:00:00 GMT  
 Summary: How to detect memory leaks better?


Fri, 19 Jun 1992 00:00:00 GMT  
 Summary: How to detect memory leaks better?

Quote:
> If you are *certain* the code will never get copied
> to another project, and the project's nature will never
> change so the leak matters, then feel free to write it as
> sloppily as you like.

    On the surface, this appears to be a good suggestion -- but my
experience is that if I do this I will not be able to sleep well at night.
Knowledge of an existing memory leak (even if the leak is harmless) can
truly torment my psyche to no end. Save yourself from this hell, my son.
Find the leak and fix it.


Mon, 28 Oct 2002 03:00:00 GMT  
 Summary: How to detect memory leaks better?


Fri, 19 Jun 1992 00:00:00 GMT  
 Summary: How to detect memory leaks better?

Quote:

> > If you need help with setting breakpoints at an allocation number, post
> > another message.

> I would appreciate some details on how to do this.

    Calling CrtSetBreakAlloc(long lAllocationNumber) will set a breakpoint
at a particular allocation number. If you want to track down several leaks
in one debug session, this will be a problem because you'll have to keep
changing the value of the allocation number that you pass to
CrtSetBreakAlloc(), recompile, etc... Another approach is to open your
"Watch" debug window and monitor the a variable called:

{,,msvcrtd.dll}_crtBreakAlloc

    You can use the Watch window to actually CHANGE this value during your
debug session. If you change the value to 4566, for instance, your program
will automatically break on the 4566th allocation. This second technique
only works if you are linking to the debug/dll version of the C Runtime
Library.



Mon, 28 Oct 2002 03:00:00 GMT  
 Summary: How to detect memory leaks better?

Quote:

>BTW, one should not use "void main()" (int would be better).

True, and I'll start using "int main()" in throwaway examples when VC
implements the return-less form properly and doesn't warn about it. In
the meantime, "void main()" remains the easiest portability mistake
you'll ever have to fix and draws attention out of all proportion to
its significance. IMO, of course. :)

Quote:
>> ... you'll find that it doesn't increase the leak count. Also
>> note that leaks reported at program exit may not be important,
>> because there's little point in freeing memory that was
>> dynamically allocated but needs to exist throughout the
>> program's execution. Freeing this memory may slow program exit
>> due to paging effects.

>If I use the dynamic allocation a lot in my application, does
>the last notice mean that I should always use mem-state and
>checkpoint functions? Or can I distinguish that "little point
>in freeing memory" case from the real (my own fault) memory
>leaks?

I'm not advocating letting things leak; I'm just pointing out that it
may not matter if you do. Leaks you must worry about include those
that grow over time and those that represent objects that should have
been destroyed but were not. If the leaks are consistent from run to
run, you can often set allocation number breakpoints to discover who
allocated the memory. You can use the checkpoint functions to help
validate areas of your own code, but if you're using C++ effectively,
you're not seeing any leaks, except for spurious ones caused by code
like MFC, which prematurely dumps leaks.

--
Doug Harrison

Visual C++ MVP



Mon, 28 Oct 2002 03:00:00 GMT  
 
 [ 13 post ] 

 Relevant Pages 

1. Summary: How to detect memory leaks better?

2. Best way to detect memory leaks

3. Tracking Memory Leaks (summary + code)

4. Best way to detect mem leaks...

5. detecting memory leaks in vc7

6. Detecting memory leaks

7. HELP:Detecting memory leaks

8. How to detect memory leak in Linux?

9. Detecting memory leaks

10. How to detect memory leaks in an ATL COM server with MFC

11. How to detect Memory Leaks ?

12. Detecting Memory Leaks efficiently

 

 
Powered by phpBB® Forum Software