prevent memory leakage from coding


by JulsSmile
Tags: coding, leakage, memory, prevent
JulsSmile
JulsSmile is offline
#1
Oct24-12, 08:08 AM
P: 10
I am studying a problem releated to memory leakage.
Now, there are many tools to check memory leak 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.
Phys.Org News Partner Science news on Phys.org
SensaBubble: It's a bubble, but not as we know it (w/ video)
The hemihelix: Scientists discover a new shape using rubber bands (w/ video)
Microbes provide insights into evolution of human language
chiro
chiro is offline
#2
Oct26-12, 12:20 AM
P: 4,570
Hey JulsSmile and welcome to the forums.

The simple solution that is used is to centralize memory allocation in one place and then use a variety of sub-systems that interface with your common code to create structures.

The basic approach that is commonly used is something known as a class factory.

http://en.wikipedia.org/wiki/Factory_method_pattern

What you can do with a class factory is behind the interface, you keep track of what has been created and store the pointers for all new allocated structures in that factory and the factory can do things like take class types and other information to return either a direct pointer to that instance or an interface pointer that lets you access the class instance from that interface.

If you use an interface pointer then it means that what you can do is let the factory deal with the real pointer so that it can do things like delete it (without the programmer doing it or trying a double delete), lock the resource (good for multi-threading) amongst other things.

Within the factory you can add an event system that broadcasts messages of when instances have been deleted, instantiated (created), modified, locked, and so on and every other thing that accesses the resource can update itself accordingly.

So not only do you take care of memory leakage, you also take care of synchronization between every single module that uses shared data.
JulsSmile
JulsSmile is offline
#3
Nov26-12, 07:07 AM
P: 10
Thanks for the answers! I'm curious to know what you prefer debuggers for Linux and for Windows?
Perhaps you prefer another methods?

rcgldr
rcgldr is offline
#4
Nov26-12, 12:56 PM
HW Helper
P: 6,931

prevent memory leakage from coding


For Windows, you can download and use microsoft visual C / C++ express which is free.

Getting back to your original question, I'm not sure there is some univeral method to avoid coding problems, whether the coding problems involve memory leakage or other issues. This is why we use debuggers and other coding tools.
D H
D H is online now
#5
Nov26-12, 11:37 PM
Mentor
P: 14,476
Quote Quote by rcgldr View Post
I'm not sure there is some univeral method to avoid coding problems, whether the coding problems involve memory leakage or other issues.
There is something that comes pretty close. Don't use raw pointers.
  • Use std::string rather than char*.
  • Use a STL container rather than a dynamically-allocated C-style array.
  • Use smart pointers such as C++11's std::unique_pointer or those from Boost if you don't have C++11.
  • If you are doing low-level programming and need to allocate memory, follow RAII religiously (wiki article: http://en.wikipedia.org/wiki/Resourc...Initialization).
  • Follow the rule of three (C++: rule of five) as well.

This won't stop the worst kind of memory leaks. Plug all the leaks reported by a tool such as valgrind and your program may still "leak." Use a language such as Java, C#, lisp, python, etc., that does automated garbage collection and your program may still "leak."

These most insidious of leaks are hard to find because the program has valid references to the memory throughout execution and because the memory is properly freed right before the program terminates. The problem is that the program should have severed those links / let variables go out of scope / deleted the allocated memory once there is no longer a need to keeping that old allocated memory around.
jhae2.718
jhae2.718 is offline
#6
Nov27-12, 01:38 AM
PF Gold
jhae2.718's Avatar
P: 1,153
Quote Quote by JulsSmile View Post
Thanks for the answers! I'm curious to know what you prefer debuggers for Linux and for Windows?
Perhaps you prefer another methods?
I'm a Linux guy, gdb and valgrind are staples.

Judiciously placed printfs are also pretty useful.
JulsSmile
JulsSmile is offline
#7
Nov27-12, 03:35 AM
P: 10
Oh! I know valgrind - the best tool for Linux! I want to know debuggers for windows ))
KumarDel
KumarDel is offline
#8
Nov28-12, 05:18 AM
P: 5
Hi all!
I can give some good debuggers that I use: purify, deleaker, memcheck.
JulsSmile
JulsSmile is offline
#9
Nov30-12, 07:21 AM
P: 10
How about vld. Is there someone who use it?
KumarDel
KumarDel is offline
#10
Apr2-13, 04:45 AM
P: 5
This tool is often used by beginners.
I can posovetovt use built-in tools to detect leaks. They do not provide 100% protection, but they can help find memory leaks.
jim mcnamara
jim mcnamara is offline
#11
Apr2-13, 07:16 AM
Sci Advisor
PF Gold
P: 1,355
There are C libraries like dmalloc that are meant specifically to debug both memory allocation and memory management.
JulsSmile
JulsSmile is offline
#12
Apr3-13, 07:05 AM
P: 10
Thanks for answers. I have already finished my researches.
But I have a new question - how to avoid memory leaks in my code? I read about memory management and there are a few tips. I'm interested in what you are doing to avoid leaks?
ScottSalley
ScottSalley is offline
#13
Apr3-13, 08:57 PM
P: 6
Most the code I've worked on (which is in C and at three different companies) uses a standard format to reduce the chances of memory leaks. The form involves:
1. Free memory at the same level of the function heiarchy it was allocated in.
a. If you have a create function, then have a delete.
b. If CreateFoo, calls CreateBar, then have a DeleteFoo that calls DeleteBar.
2. If an error happens in a function, free all memory allocated by that function before returning. [see example]
a. If the erorr happens in CreateFoo, try to use DeleteFoo to do the cleanup. Or a helper function that is also used by DeleteFoo.
b. Use separate variables for the local object creation from the pointers used to return an object.
3. Make all the error handling in each function as similar to other functions as possible.
int CreateBar(struct Bar **ppBar)
{
int error = 0;
struct Bar *pBar = NULL;

bar = malloc(....);
ERROR_IF_NULL(bar);

*ppBar = pBar;
cleanup:
return error;
error:
DeleteBar(pBar);
pBar = NULL;
goto cleanup;
}
rcgldr
rcgldr is offline
#14
Apr3-13, 10:45 PM
HW Helper
P: 6,931
What I often do is have a single exit point for a function that releases any potentially opened or allocated resource:

    handle = INVALID_HANDLE_VALUE; /* initialize handles to invalid */
    ptrtomem = NULL;  /* initialize pointers used for allocation to NULL */

/* ... */

common_exit: /* close or free any open or allocated resources */
    if(handle != INVALID_HANDLE_VALUE)
        close(handle);
    if(ptrtomem != NULL)
        free(ptrtomem);
    return;
Borek
Borek is online now
#15
Apr4-13, 02:34 AM
Admin
Borek's Avatar
P: 22,710
It doesn't help with memory leakage, but to help myself clean things up I often initialize all pointers to NULL first (just like rcgldr did in his code), then delete them using

#define DELETEPTR(__ptr__) { if (__ptr__) { delete __ptr__; __ptr__ = NULL; }}
This way I don't have to care about when the program stopped to work and which objects were already created.
KumarDel
KumarDel is offline
#16
Apr4-13, 06:00 AM
P: 5
Do not use dynamic memory
rcgldr
rcgldr is offline
#17
Apr4-13, 10:19 AM
HW Helper
P: 6,931
Quote Quote by Borek View Post
It doesn't help with memory leakage, but to help myself clean things up I often initialize all pointers to NULL first (just like rcgldr did in his code), then delete them using

#define DELETEPTR(__ptr__) { if (__ptr__) { delete __ptr__; __ptr__ = NULL; }}
This way I don't have to care about when the program stopped to work and which objects were already created.
Yes, I forgot to mention that if one of my programs does any closing of handles or freeing of memory within the program (versus at the exit point), I also have to set handle values back to INVALID_HANDLE_VALUE after closing and pointers back to NULL after freeing memory. Borek's idea of using a macro to do both seems like a good idea, for handles it could be:

#define CLOSEHANDLE(__hdl__) \
  { if (__hdl__ != INVALID_HANDLE_VALUE) \
      { close(__hdl__); \
        __hdl__ = INVALID_HANDLE_VALUE; }}
JulsSmile
JulsSmile is offline
#18
Apr5-13, 04:44 AM
P: 10
I am very grateful!
Many thanks to ScottSalley!!!
Your explanation I printed and hung at the computer!


Register to reply

Related Discussions
What's the difference between short term memory and working memory? Biology 6
How do memory metals (Shape-memory alloys) work? Biology, Chemistry & Other Homework 0
Muscle memory or normal memory? General Discussion 1
How to let the cold work shape memory alloy to acquire shape memory properties Materials & Chemical Engineering 2
Verbal memory/semantic memory, also long-term memory Social Sciences 0