Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Jun 12th, 2008, 12:06 AM   #1
ChevyCowboy15
Newbie
 
ChevyCowboy15's Avatar
 
Join Date: Nov 2007
Location: Central USA
Posts: 19
Rep Power: 0 ChevyCowboy15 is on a distinguished road
Memory Leaks

i was reading about how programmers cause memory leaks... and i was just wondering how do you keep from causing memory leaks?? and how can you cause a memory leak??
ChevyCowboy15 is offline   Reply With Quote
Old Jun 12th, 2008, 12:43 AM   #2
Jimbo
Battle Programmer
 
Jimbo's Avatar
 
Join Date: Feb 2006
Location: Bellevue, WA, USA
Posts: 763
Rep Power: 3 Jimbo is on a distinguished road
Re: Memory Leaks

Causing memory leaks is simple: you simply allocate space and don't delete/free it later. For instance:
int* somePtr = new int;
somePtr = new int[4]; // leak the first int, since we can no longer free it
somePtr = new int;// leak the 4 ints worth, since we can't free them

Preventing leaks is "merely" a matter of making sure you free whatever you've allocated. I put merely in quotes because while it sounds easy, there are lots of little nuances that can cause these issues. But for the most part, be careful and you'll get a decent head start.
__________________
<insert disclaimer here>
<insert shameless plug for Visual Studio here>
Jimbo is offline   Reply With Quote
Old Jun 12th, 2008, 9:07 AM   #3
JD-Salinger
Unknown
 
JD-Salinger's Avatar
 
Join Date: Apr 2008
Location: unknown
Posts: 87
Rep Power: 1 JD-Salinger is on a distinguished road
Re: Memory Leaks

you can cause memory leaks during
1. Normal execution of your program ( allocated resources using new and unfreed it without using delete)
2. when propagating an error, when an exception occured
__________________
-------------------------------------------------------------------------
I thought what I'd Do was, I'd pretend to be one of those deaf mutes
------------------------------------------------------------------------
JD-Salinger is offline   Reply With Quote
Old Jun 12th, 2008, 5:34 PM   #4
ChevyCowboy15
Newbie
 
ChevyCowboy15's Avatar
 
Join Date: Nov 2007
Location: Central USA
Posts: 19
Rep Power: 0 ChevyCowboy15 is on a distinguished road
Re: Memory Leaks

on beginner programs like the "Hello" program and just beginner programs can you cause memory leaks?
ChevyCowboy15 is offline   Reply With Quote
Old Jun 12th, 2008, 6:06 PM   #5
JD-Salinger
Unknown
 
JD-Salinger's Avatar
 
Join Date: Apr 2008
Location: unknown
Posts: 87
Rep Power: 1 JD-Salinger is on a distinguished road
Re: Memory Leaks

You cant cause you havent acquired any resources. The concept is when you acquire any resources you should release that, resources are on the form of memory,file handles, semaphores,reference counts etc. so if you acquire any resource you should release it.
__________________
-------------------------------------------------------------------------
I thought what I'd Do was, I'd pretend to be one of those deaf mutes
------------------------------------------------------------------------
JD-Salinger is offline   Reply With Quote
Old Jun 12th, 2008, 8:44 PM   #6
ChevyCowboy15
Newbie
 
ChevyCowboy15's Avatar
 
Join Date: Nov 2007
Location: Central USA
Posts: 19
Rep Power: 0 ChevyCowboy15 is on a distinguished road
Re: Memory Leaks

oh alrighty that makes me feel better i was just curious thanks for the help
ChevyCowboy15 is offline   Reply With Quote
Old Jun 13th, 2008, 7:09 AM   #7
lectricpharaoh
Caffeinated Neural Net
 
lectricpharaoh's Avatar
 
Join Date: Jun 2005
Location: Dry west coast of Canada
Posts: 1,034
Rep Power: 5 lectricpharaoh will become famous soon enough
Re: Memory Leaks

Memory leaks are specific to memory, but there are similar problems for other resources (handles to OS objects like files, sockets, etc). Basically, when you allocate memory or grab a resource from the OS, you need to deallocate it or return it to the OS when you're done. Failing to do so will generally cause slow (or not so slow, depending) degradation of system performance.

In C++, when you allocate memory, you receive a 'pointer' to this memory. A pointer is simply an address, or more precisely, a variable containing an address. When you free memory, you need to tell the system what memory block to free. This is done by passing the pointer (received when allocating the memory) to a free function. In C, allocation is done with malloc() or similar functions, while freeing memory is done with free(). In C++, it's generally done with new and delete, but you can still use C-style semantics if you like. Either way, if you allocate memory, and then overwrite the only copy of the pointer, you can no longer free it:
int *array = new int[32];  // create a dynamic array of 32 ints
array = new int[64]; // naive attempt to 'resize' it to 64 elements
delete[] array;  // only recovers the 64-element block; the 32-element block is lost for good
I realize that this is basically what Jimbo posted in his code block, but hopefully it shows you why you can no longer free it.

Of course, this type of memory leak actually prevents you from freeing some memory. It's also possible to simply forget to do it, and if you're doing this inside a function, you'll lose the pointer when the function exits (unless it's static, of course). Once you lose the pointer in this way, you're back to the 'unfreeable' situation above.

As for other resources, many of these (particularly ones received directly from the OS) are represented as pointers to internal structures. These pointers are often called 'handles', and they need to be returned to the OS when you're done. For example, in Windows programming, when you want to 'draw' in a window, you need a handle to a 'device context'. Since the system has a limited number of these, if you fail to return them, at some point many programs will be unable to update their windows, and it will all be your fault.

One technique for avoiding memory leaks (and, to a lesser extent, other resource leaks, depending on the implementation) is to use a language that is 'garbage collected'. Basically, in a language with a garbage collector, the system keeps track of all references (read: pointers) that the program has, as well as all memory objects that have been allocated. If the GC detects that there is an object to which the program no longer has a reference, it will reclaim the memory (eventually). Using a language with a GC has certain performance implications, both good and bad, but it does make it pretty hard for a programmer to create memory leaks. However, you know the saying about making something foolproof, and the world will breed a more ingenuous fool- in other words, some idiots will still manage to confuse the collector and cause resource leaks.
__________________
And once again, Probability proves itself willing to sneak into a back alley and service Drama as would a copper-piece harlot.
- Vaarsuvius, Order of the Stick
lectricpharaoh is offline   Reply With Quote
Old Jun 13th, 2008, 8:26 AM   #8
Soulstorm
Hobbyist Programmer
 
Soulstorm's Avatar
 
Join Date: Jan 2006
Location: Menidi, Athens, Greece
Posts: 243
Rep Power: 3 Soulstorm is on a distinguished road
Re: Memory Leaks

Quote:
Originally Posted by lectricpharaoh
One technique for avoiding memory leaks (and, to a lesser extent, other resource leaks, depending on the implementation) is to use a language that is 'garbage collected'. Basically, in a language with a garbage collector, the system keeps track of all references (read: pointers) that the program has, as well as all memory objects that have been allocated. If the GC detects that there is an object to which the program no longer has a reference, it will reclaim the memory (eventually). Using a language with a GC has certain performance implications, both good and bad, but it does make it pretty hard for a programmer to create memory leaks. However, you know the saying about making something foolproof, and the world will breed a more ingenuous fool- in other words, some idiots will still manage to confuse the collector and cause resource leaks.
Actually, using garbage collection is a bad programming practice in my opinion. The programer will not learn the true meaning of manual memory allocation and deallocation. I mostly program in ObjC, and Apple has released ObjC 2.0, which has a modern garbage collector in it. I prefer not using it, not only to ensure backwards compatibility, but also because I want to learn the concepts of memory leaks, even if that means falling into memory traps.

Garbage collectors must be used by professionals, who already know what they are doing.
__________________
Project::Soulstorm (personal homepage)
Soulstorm is offline   Reply With Quote
Old Jun 13th, 2008, 5:37 PM   #9
grumpy
Programming Guru
 
grumpy's Avatar
 
Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,223
Rep Power: 5 grumpy is on a distinguished road
Re: Memory Leaks

I tend to agree with soulstorm on garbage collection. Garbage collectors are useful, if they are used in a disciplined manner, but it takes a lot of effort to use them properly. In practice, it is often treated like a safety net by programmers that is assumed to "just work", so no thought is given to questions of questions like object lifetime.

Even worse, GC only really works for one type of resource (memory within a program: it does not work well for memory resources that are shared between programs) and the same thinking, in practice, carries over to working with other resources so programmers neglect to close sockets, pipes, mutexes, open files .... all resources that are finite and, in practice, are more scarce than memory.

I have seen largish client/server systems in which both client and server were implemented in languages that used garbage collection. One common trap is that servers allocate resources (memory, locks, connections to back end databases) for each client connection, and does not deallocate them until the client connection closes. Problem comes when a long-running client opens a connection and there is no thought about the lifetime of that connection so, practically, the client simply loses track of it and the connection is kept open indefinitely until the client is terminated. It does not take particularly many such clients to bog down the server. This is a resource leak in a server that is directly attributable to incomplete client design; while these scenarios had problems on the server end (eg how the servers detected closed connections, which can be a challenging problem in itself), the root cause was simply that the programmers implementing the clients did not think about resource lifetime and client resource leaks (of sockets conections!) caused leaks in the server.

Incidentally, not all garbage collectors are based on keeping track of references. Mark and sweep collectors (such as that used in Java) simply do a search through the memory space, and match values of memory addresses with values of variables.
grumpy is offline   Reply With Quote
Old Jun 14th, 2008, 5:03 AM   #10
Jabo
Not a user?
 
Join Date: Sep 2007
Posts: 272
Rep Power: 2 Jabo is on a distinguished road
Re: Memory Leaks

So you would, in theory, have to calculate how much memory your program should use and compare it to how much it's actually using to know if you have a memory leak?

I'm sure there are probably gray areas in this approach, like how much memory would a socket use? Equal to how much buffer the socket is given? Any "free" approaches to memory detection (by free, I mean do your own work and not relying on somebody's else's program to do it for you)?

Also, how do you know how much memory a form consumes with 15 various controls on it? Is there a resource somewhere that tells you this? I'm asking because I have a simple (in my eyes) little program that I wouldn't think would take up more that 5 MBs of memory, but when you launch it, it consumes nearly 20 MB upon loading and running.
Jabo is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Please suggest a C++ source code analysis tool for debugging memory leak Michael_24 C++ 3 Apr 22nd, 2008 11:06 AM
an efficient way to store/lookup memory addresses? rgba Software Design and Algorithms 8 Feb 13th, 2008 1:54 AM
Hexadecimal Memory Address Question 357mag C++ 1 Jul 8th, 2007 9:19 PM
Difficulties with memory leaks and the STL + boost Jessehk C++ 5 Nov 26th, 2006 12:17 PM
Heap vs. Stack memory Eric the Red C++ 11 Oct 24th, 2006 6:18 PM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 8:32 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC