?
Solved

What are the 3 most common reasons to cause memory leak in C/C++?

Posted on 2007-10-08
9
Medium Priority
?
1,059 Views
Last Modified: 2013-12-14
Hi experts,

I know that without calling "free/delete" in C/C++ causes memory leaks. Besides this what are other most common reasons to cause memory leaks in C/C++?

Thanks a lot.
0
Comment
Question by:davidw88
9 Comments
 
LVL 4

Expert Comment

by:jimstar
ID: 20038548
Some APIs will allocate memory themselves and pass back allocated memory (I can't think of any off the top of my head, but I know I've seen it). In those cases, you have to ensure you free that memory that is passed back.
0
 
LVL 4

Accepted Solution

by:
jimstar earned 750 total points
ID: 20038599
Another one would be not releasing a handle. For example, if you use LoadLibrary to load a DLL, that DLL will not unload until you use FreeLibrary on the DLL's handle returned from LoadLibrary (or until your process unloads, when it will free up just like malloc'd memory would).

Any handle that you get in Windows usually needs to be closed, such as via CloseHandle(), FreeLibrary(), etc depending on the handle type.

And I just remembered - a case of an API allocating memory itself that needs freed (from my post above) would be AllocateAndInitializeSid (http://msdn2.microsoft.com/en-us/library/aa375213.aspx), which requires that you call FreeSid() on the returned sid, otherwise that will be a leak.
0
 
LVL 30

Expert Comment

by:Axter
ID: 20038674
The following are other functions that can cause memory leaks:

_strdup
realloc
calloc

SysAllocString            
SysAllocStringByteLen
SysReAllocString      
SysAllocStringLen      
SysReAllocStringLen


Check out the following link for other functions that can cause memory leaks and handle leaks:
http://code.axter.com/leaktracker.h

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 4

Expert Comment

by:jimstar
ID: 20038677
GlobalAlloc and LocalAlloc too.
0
 
LVL 4

Expert Comment

by:jimstar
ID: 20038722
Plus: GlobalReAlloc/LocalReAlloc and any of the other heap management functions (HeapAlloc, CreateHeap, etc). Additionally VirtualAllocEx, AllocateUserPhysicalPages, etc.

These are definitely not "top 3", but if you're doing drivers or native apps, you also might have: AllocateCommonBuffer, NtAllocateVirtualMemory, NtAllocateUserPhysicalPages, NtCreateSection, RtlAllocateHeap, RtlAllocateHandle, RtlAllocateAndInitializeSid, RtlDuplicateUnicodeString, etc.

Essentially, anywhere that memory is allocated, there must be an associated free, and it all boils down to that. All of the functions that have been mentioned above allocate memory in some way. When that memory is not freed, it's a memory leak.

0
 

Expert Comment

by:sjith2000
ID: 20038763
>>Some APIs will allocate memory themselves and pass back allocated memory.
I just want to add one more point to what jimstar says.
C++ programmers use many  libraries.Once while I was attending a C++ training, I remember that the trainer was saying like "STL do all the memory manegemnt for us, but it has lots of memory leaks".So they don't use the STL for critical applications like embedded systems and all(I don't know how many people agree to this).
0
 
LVL 12

Expert Comment

by:weareit
ID: 20038776
A little less complicated than the above mentioned but one of the most common that I have seen is where someone declares a NEW pointer but does not unallocate/DELETE the memory associated with it when they are finished.

-saige-

0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 20038909
>>>> I know that without calling "free/delete" in C/C++ causes memory leaks.

Actually other reasons are less important.  It is clear, that if calling some 'alloc' function you need to call the  corresponding 'free'. Normally, a good program design should prevent from allocating memory in a function and have to free in another function. In C++ use classes to allocate in the consructor or any 'create' function and delete in the destructor. But of course you need to delete the class object if created on the heap (by 'new') or the destructor won't be called. The thre main reasons for leaks are

1. forgetting to free/delete
2. returning without freeing/deleting
3. assigning a new allocation to a pointer without deleting the old one.

Some less common reasons:

4. Overwriting pointers by writing beyond array boundaries
5. Using global or static member pointers
6. Allocating memory without storing the pointer, e. g.  func(new int[100]);

Regrads, Alex
0
 
LVL 10

Expert Comment

by:peetm
ID: 20038927
The definition of a memory leak is the loss of a dynamically allocated block of memory because all references to it are lost.

Assigning the return value of malloc() to a local variable in a function, and then exiting the function without returning the contents of that variable is one common example of a memory leak.

Also, setting another pointer via realloc(). to the original set via malloc() then later freeing the malloc'ed one is likely to cause problems too.

strdup() is a standard C function that requires freeing - but perhaps you've got that covered as you mention free().
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Article by: evilrix
Looking for a way to avoid searching through large data sets for data that doesn't exist? A Bloom Filter might be what you need. This data structure is a probabilistic filter that allows you to avoid unnecessary searches when you know the data defin…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question