PDA

View Full Version : Memory leak prevention methodogies



c___newbie
11-12-2007, 03:27 AM
Hi all,
Iím studying a problem releated to memory leakage.
Now, there are many tools to check memory leakake at run-time (dynamic analysis), and some tools can check memory leakage at compile-time (static analysis). But I have some questions:
How do you think to prevent memory leakage from coding phase (without using tool)? (or In coding phase, what do you have to do to prevent memory leakage?)
I want to investigate from many programmers in many countries.
Can you help me?

Elysia
11-12-2007, 03:32 AM
Use memory managers or shared pointers, such as boost's shared_ptr, define responsibility for who should clean up the memory and make common exit sections in functions so that everything is cleaned up and set your pointers to NULL when not needing them anymore.
That's what I can think of.
This is coding phase, of course.

c___newbie
11-12-2007, 03:45 AM
Thanks!
I'm searching information on internet and I found 2 solutions:
- Using coding check list (or coding guide line)
- Using template library to reduce memory leakage (for ex: vector, list, queue, auto_ptr...)
and I need more information than that ...

matsp
11-12-2007, 04:24 AM
Well, for any larger program, it's almost impossible to investigate all paths that MAY be taken for a given program - so whilst static analyzis can spot OBVIOUS mistakes, e.g. there is an allocation, but no pointer is kept after the function exits:


void somefunc(char *s)
{
char *p;

p = malloc(strlen(s)+1);
strcpy(p, s);
.... modify and mess about with p
.... no call to free.
}


But if this function were to return the value of p to the calling code, you'd have to follow the calling code to find out if p is maintained - after several branches, loops and conditionals, there may well be a situation where it can't be made certain that the code is correct or not.

Dynamic analyzis is easier to implement - just track allocations and when the application exits, if there's any unfreed objects, those are memory leaks!

--
Mats

CornedBee
11-12-2007, 06:05 AM
Use RAII religiously. Don't allocate any resource that isn't released by a destructor.

Once you really do that, the only remaining problem comes from owner cycles. To avoid these, do as Elysia said and define clear ownership rules for your objects.

Elysia
11-12-2007, 09:23 AM
Thanks!
I'm searching information on internet and I found 2 solutions:
- Using coding check list (or coding guide line)
- Using template library to reduce memory leakage (for ex: vector, list, queue, auto_ptr...)
and I need more information than that ...

Yes, you should use thoroughly tested objects rather than making your own to avoid memory leaks. Using vectors instead of arrays is a good thing to make sure you don't get leaks.
There are, of course, coding guidelines to follow (like classes are in charge of their own memory - they do not give out pointers willingly to memory allocated by themselves and they should NEVER allow any outside function to delete its memory [in such case, a member function can be used to delete that memory]).

Another good idea to avoid allocating on the heap, if possible. Pass by reference or by value, if it can be done.
Take care to note the lifetime of your objects. Should they last the entire life of the app? Then free them when the app exits. If not, then free it after you're done with it.
If a function allocates memory that another part of the code requires, a good guidelines is that the function that now allocated the memory will give up ownership to the other part of the code that gets the memory and hence THAT part will be responsible for cleanup.
In general, it's also a good idea that a function that allocates the memory also frees it.

CornedBee
11-12-2007, 10:38 AM
In general, it's also a good idea that a function that allocates the memory also frees it.
I think there's room for misunderstanding here.

It is preferable that any function that allocates memory also frees it before it returns. However, sometimes memory (or any other resource) must outlive the function call. Don't misunderstand the above statement to mean that you should one function both for allocating and freeing a resource.

(By the way, Elysia, I'm surprised. Have we converted you?)

Elysia
11-12-2007, 10:40 AM
I think there's room for misunderstanding here.

It is preferable that any function that allocates memory also frees it before it returns. However, sometimes memory (or any other resource) must outlive the function call. Don't misunderstand the above statement to mean that you should one function both for allocating and freeing a resource.
Of course, that's what I mean. If the memory is to be freed, let it (if possible) be the function that allocated it. If it must outlive the function, consider setting rules for how. Is it a function that creates an object and returns it? Then the function that takes it might free it, for example.


(By the way, Elysia, I'm surprised. Have we converted you?)
:D I watch and learn :p

Perspective
11-12-2007, 01:13 PM
Use some software model checking techniques (formal methods).

VirtualAce
11-12-2007, 06:40 PM
...Another good idea to avoid allocating on the heap, if possible...

Proper cleanup of pointers is not what I would consider part of a design decision whether or not to use objects on the heap. C++ Programmers should know how to clean up heap objects.
Design is what necessitates the use of the heap or lack of the use of the heap. So don't take that statement as you should always opt for or gravitate towards using non-heap objects. If you follow much of the advice given in this thread then you won't have any trouble managing memory.

I find that in managed 'safe' languages like C# the lack of control given to me over my objects and their lifetime is quite an insult and normally flies in the face of what I want to do rather than assist me.

One convention I've accustomed myself adhering to in unmanaged C++ is:

m_pPointerToObject
This is a pointer and it's owned by the class. So when you see:
delete m_pPointerToObject in your code you know you are deleting an owned pointer.

m_psPointerToObject
This is a pointer but it's not owned by the class. When you see delete m_psPointerToObject you know something is amiss since you are deleting a shared pointer.

Any convention is only as good as the programmer using it and this one is not idiot proof by any means. But if you follow this convention it should be easier to spot places where you are attempting to delete a pointer that someone else may still be using or need. Likewise a function that returns a shared pointer may also use a similar convention so that you know it is returning a shared pointer.

Likewise the crtdbg library has tons of memory debugging features that will help you and the MSVC Debugger is quite good. Functions in crtdbg will tell you everything you want to know and a whole lot of stuff you didn't want to know about the memory.

brewbuck
11-12-2007, 09:20 PM
I want to investigate from many programmers in many countries.
Can you help me?

An approach nobody has mentioned yet:

Don't use new/delete. You can't leak what you haven't allocated.

EDIT: Okay, it has been mentioned.

Elysia
11-12-2007, 09:37 PM
Proper cleanup of pointers is not what I would consider part of a design decision whether or not to use objects on the heap. C++ Programmers should know how to clean up heap objects.
Design is what necessitates the use of the heap or lack of the use of the heap. So don't take that statement as you should always opt for or gravitate towards using non-heap objects. If you follow much of the advice given in this thread then you won't have any trouble managing memory.
Of course you should use heap objects when you need them, but the general idea is to avoid them IF you don't need them. What you don't create, you don't need to free.


m_pPointerToObject
This is a pointer and it's owned by the class. So when you see:
delete m_pPointerToObject in your code you know you are deleting an owned pointer.

m_psPointerToObject
This is a pointer but it's not owned by the class. When you see delete m_psPointerToObject you know something is amiss since you are deleting a shared pointer.

Wow. Good advice. I'll put that to mind.

c___newbie
11-13-2007, 08:52 PM
Ok, thanks for all comments, ideas, and experiences.
This is very useful when apply them in coding phase.

VirtualAce
11-15-2007, 08:24 PM
Of course you should use heap objects when you need them, but the general idea is to avoid them IF you don't need them. What you don't create, you don't need to free.


Sorry but that is not my methodology or line of thinking about the design of my code. I know how to properly use memory and understand intimately the lifetime of my objects. Therefore whether I use heap objects or stack objects is purely a moot point. Every C++ programmer should understand how to use the heap. If you understand the heap and understand how to properly use it, I see no issues.

I do not follow a general rule of AVOID heap objects. Everything is a tool and I just use the right tool at the right time for the right task.

brewbuck
11-15-2007, 10:10 PM
Of course you should use heap objects when you need them, but the general idea is to avoid them IF you don't need them. What you don't create, you don't need to free.Sorry but that is not my methodology or line of thinking about the design of my code. I know how to properly use memory and understand intimately the lifetime of my objects. Therefore whether I use heap objects or stack objects is purely a moot point. Every C++ programmer should understand how to use the heap. If you understand the heap and understand how to properly use it, I see no issues.

Reading what you quoted, it says: "Use the heap when you need it. Don't use the heap when you don't need it." You say you disagree. Which part of that statement do you disagree with? The part about using the heap when you need it? Or the part about not using it when you don't?

So, you seem to be making at least one, possibly both, of these two statements:

1. You use the heap in cases where it is inappropriate.
2. You do not use the heap in cases where it is the only way to do things.

Which one of these statements are you making, if any?

By using new/delete in cases where the goal could easily be accomplished another way, is to deliberately regress to a C-like worldview and all the difficulties that entails, and seems to miss the entire point of C++.

Elysia
11-15-2007, 10:25 PM
Sorry but that is not my methodology or line of thinking about the design of my code. I know how to properly use memory and understand intimately the lifetime of my objects. Therefore whether I use heap objects or stack objects is purely a moot point. Every C++ programmer should understand how to use the heap. If you understand the heap and understand how to properly use it, I see no issues.

I do not follow a general rule of AVOID heap objects. Everything is a tool and I just use the right tool at the right time for the right task.

Sure, you can use heap objects whenever you want, but you can't escape from the fact that when you do, you'll also be introducing potential bugs in your code, beucase those objects must be freed, whether you like it or not.
So in essence, if you avoid heap objects, you don't need to free. Simple as that.
It's a good way to avoid leaks, but it's up to everyone to or not to follow the rule.

CornedBee
11-16-2007, 04:55 AM
I think Bubba means that he finds an explicit rule about avoiding heap objects superfluous, because he formulates the same rule in a positive way: use the right tool for the right job.

But having seen what some Java programmers do when they learn C++, I'm not sure I can agree with that. Habits can be hard to get rid of.

VirtualAce
11-17-2007, 03:45 AM
Yeah well to each their own. And brewbuck.........what?