Prevent memory leakage from coding

In summary: I have also found using smart pointers, such as std::unique_pointer in C++11, to be very helpful in managing memory and avoiding leaks. These pointers automatically delete the allocated memory when they go out of scope, eliminating the need for manual memory management. Additionally, using containers such as std::vector or std::map can also help avoid leaks by handling the memory management for you.
  • #1
JulsSmile
10
0
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.
 
Last edited:
Technology news on Phys.org
  • #2


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 let's 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.
 
  • #3


Thanks for the answers! I'm curious to know what you prefer debuggers for Linux and for Windows?
Perhaps you prefer another methods?
 
  • #4


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.
 
  • #5


rcgldr said:
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/Resource_Acquisition_Is_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.
 
  • #6


JulsSmile said:
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.
 
  • #7


Oh! I know valgrind - the best tool for Linux! I want to know debuggers for windows ))
 
  • #8


Hi all!
I can give some good debuggers that I use: purify, deleaker, memcheck.
 
  • #9


How about vld. Is there someone who use it?
 
  • #10
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.
 
  • #11
There are C libraries like dmalloc that are meant specifically to debug both memory allocation and memory management.
 
  • #12
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?
 
  • #13
Avoiding memory leaks with C

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;
}
 
Last edited:
  • #14
What I often do is have a single exit point for a function that releases any potentially opened or allocated resource:

Code:
    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;
 
  • #15
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

Code:
#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.
 
  • #16
Do not use dynamic memory
 
  • #17
Borek said:
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

Code:
#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:

Code:
#define CLOSEHANDLE(__hdl__) \
  { if (__hdl__ != INVALID_HANDLE_VALUE) \
      { close(__hdl__); \
        __hdl__ = INVALID_HANDLE_VALUE; }}
 
  • #18
I am very grateful!
Many thanks to ScottSalley!
Your explanation I printed and hung at the computer!
 
  • #19
What I do to avoid memory leaks is use .NET. It is really pretty difficult to crash a machine using the .NET libraries, and it has very good performance. It is also available for Linux. I did program extensively in C for many years, and my belief is, no matter how "good" you are, how "good" your tools are, and how "good" your design is, if you use C or C++ and program directly in the OS's libraries, you WILL sooner or later get a memory leak, and it may take you a long time to realize it.

Alternatively, you could use Java--or any strongly typed, modern language besides C or C++.
 
  • #20
Thanks for the advice. But even in Java garbage collector does not solve the problem with memory leaks completely.
 
  • #21
.NET mostly solves the issue of defragging memory when there is is a lot of allocation and freeing of memory, which can create a fragmentation problem even if there are no memory leaks. It does this by occaionally pausing the application and defragging (repacking) memory.
 
  • #22
JulsSmile said:
Thanks for the advice. But even in Java garbage collector does not solve the problem with memory leaks completely.

I don't understand this statement. As far as I know, the JVM and the .NET framework do not have memory leaks at all.
 
  • #23
rcgldr said:
.NET mostly solves the issue of defragging memory when there is is a lot of allocation and freeing of memory, which can create a fragmentation problem even if there are no memory leaks. It does this by occaionally pausing the application and defragging (repacking) memory.

.NET periodically releases unused memory via a special thread that runs in the background, which is imperceptible to the application--the program does not pause. .NET's garbage collector runs only very rarely, and only if an application runs out of memory (in which case, the application actually stops running until the garbage collector completes its task, which can introduce a noticeable pause).
 
  • #24
harborsparrow said:
I don't understand this statement. As far as I know, the JVM and the .NET framework do not have memory leaks at all.

It's not a very simple question. There are not memory leaks in C + + understanding. Memory leaks in Java have a slightly different mechanism of occurrence, that's what hi meant
 
  • #25
harborsparrow said:
What I do to avoid memory leaks is use .NET. [...] if you use C or C++ and program directly in the OS's libraries, you WILL sooner or later get a memory leak, and it may take you a long time to realize it.

But isn't that comparing apples with oranges?
Application layer development with close to the OS programming?

Even when I use boost or MPI libs from C++ I don't mess around with sockets, buffers, mallocs and stuff manually, but rely on the robustness of lower layers for those needs.

As you rely on the coding done by MS folks when you use .NET, don't you?
 
  • #26
Solkar said:
Even when I use boost or MPI libs from C++ I don't mess around with sockets, buffers, mallocs and stuff manually, but rely on the robustness of lower layers for those needs.

As you rely on the coding done by MS folks when you use .NET, don't you?

.NET libraries have undergone use and testing by millions of people by the time I get hold of them, so they have pretty much had any bugs ironed out. Of course, Microsoft libraries could have bugs in them, but it's in the interest of Microsoft to make these things stable, and they are quite good at that at this point.

If you use a language such as Java or C# (or any .NET language) that runs on a framework, it will be less likely to crash, firstly because the languages themselves are strongly typed and take care of allocation and reclaiming automatically with well-tested strategies, and secondly because each process runs in a protected environment such that a poorly-behaved process is not allowed to crash the machine. Also, these languages are just-in-time compiled, which means that once they "warm up" (once most of the code has executed at least once), they are running as native code and run about as fast as C or C++ programs. This is why these languages are so popular and successful, especially for use on web servers. Safety and good behavior sharing a machine.

There are times when you need to code down to the metal, and then, and ONLY THEN, would I choose to use C or C++ directly.
 
  • #27
harborsparrow said:
If you use a language such as Java or C# (or any .NET language) that runs on a framework, it will be less likely to crash, firstly because the languages themselves are strongly typed and take care of allocation and reclaiming automatically with well-tested strategies, and secondly because each process runs in a protected environment such that a poorly-behaved process is not allowed to crash the machine.

Spooky... why the heck do I feel like in a SUN, IBM or MS sales event of about year 2000 when I read this?

In fact it's ages ago that I've seen a C/C++/Fortran binary of mine crashing a machine.
Sometimes they overheat a node, which is shut down then, but that's a cooling, not a coding issue.

harborsparrow said:
Also, these languages are just-in-time compiled, which means that once they "warm up" (once most of the code has executed at least once), they are running as native code and run about as fast as C or C++ programs.

This is somewhat amusing - on one hand there's this magic that protects the app and the OS whenever required, and, foremost, the universe from coders of doom.
On the other hand it seems to magically disappear when it comes to performance issues.

For about 20 years yet, I've read about Java either that
- its bad performance is simply not existent and my profiling plainly wrong. Period.
- Or that the very version will fix exactly that (whatever) issue.
 

1. What is memory leakage in coding?

Memory leakage in coding refers to a situation where a program does not release the allocated memory after its use. This can lead to a gradual decrease in available memory, causing the program to slow down or crash.

2. What causes memory leakage in coding?

Memory leakage can be caused by a variety of factors such as not properly deallocating memory, use of global variables, and not handling exceptions properly. It can also be a result of coding errors or inefficient algorithms.

3. How can memory leakage be prevented in coding?

To prevent memory leakage, it is important to properly manage and deallocate memory after its use. This can be achieved by using tools such as garbage collectors or manual memory management techniques. It is also important to write efficient and error-free code to avoid unnecessary memory usage.

4. What are the consequences of memory leakage in coding?

The consequences of memory leakage can range from minor performance issues to program crashes and system failures. It can also lead to security vulnerabilities as hackers can exploit memory leaks to gain access to sensitive data.

5. How can one identify and fix memory leakage in coding?

Memory leakage can be identified by using debugging tools such as memory profilers or by analyzing system performance. Once identified, it can be fixed by carefully reviewing the code and making necessary changes to properly allocate and deallocate memory. It is also important to conduct regular testing and debugging to catch and fix memory leakage early on.

Similar threads

  • Programming and Computer Science
Replies
17
Views
1K
  • Programming and Computer Science
Replies
7
Views
554
  • Programming and Computer Science
Replies
6
Views
989
  • Programming and Computer Science
Replies
1
Views
172
  • Programming and Computer Science
Replies
3
Views
1K
  • Programming and Computer Science
Replies
14
Views
1K
  • Programming and Computer Science
Replies
5
Views
794
  • Programming and Computer Science
Replies
13
Views
1K
  • Programming and Computer Science
Replies
1
Views
3K
Back
Top