Click here to Skip to main content
Click here to Skip to main content

Memory Management for Beginners

, 2 May 2004
Rate this:
Please Sign up or sign in to vote.
This article explains the basic concepts in memory management in C++ and MFC

Introduction

Memory management is important for every programming language. The memory management may be Manual or Automatic. The automatic memory management is a Garbage Collection Technique. Garbage collection is a technique use to deallocate memory automatically when control flow goes to out of scope. The programmer doesn't concentrate on freeing the memory if the programming language supports garbage collection. Java and .NET enabled languages support the garbage collection features.

The manual memory management is the technique where the memory is controlled by the programmer. Programming languages like C or C++ use manual memory management. We allocate memory using C run time library functions or C++ new operator. C++ provides programmers ways to allocate and deallocate memory using new and delete operator.

Memory management in C/C++:

Memory management in C uses malloc, realloc and calloc functions to allocate the memory. The free function is used to free the memory. The malloc function is used to allocate the block of memory in heap. The realloc function is to reallocate the memory; if programmer allocates the memory using malloc, if he/she wants to extend the memory use realloc function. The calloc function is to allocate the array of memory and initialize to 0. Microsoft C supports debug versions of each malloc, calloc and realloc functions. The free function is to free the memory. The free function also supports debug version. The debug version functions only arise if the compiler set to debug mode. Microsoft C supports extended memory using extended functions.

Some programs continually allocate memory without ever giving it up and eventually run out of memory. It is called Memory Leak. If the programmer allocates memory using new or C run time library functions and he/she doesn't remember to release the memory in that situation memory leak has occurred. So, the programmer handles memory efficiently and effectively.

Programming language like C is meant for allocate and reallocate features. But, in C++ there are no equivalent operators (Refer Stroustrup style and Technique FAQ Page). So, we use new operator to extend the memory. When programmer uses vector elements (Static template Library), the user need not be concerned with the allocation and deallocation of memory. Because, the vector automatically destroy the memory when it goes to out of scope.

The manual memory management takes lot of code. The memory controlled by the programmer. So, we effectively control the memory. C/C++ supports the garbage collector explicitly using any of garbage collector.

C++ memory Management Techniques:

Microsoft suggested don't intermix with C runtime library and C++ new/delete operators. Suppose, if you allocate memory using new, you compulsorily deallocate memory using delete operator. Don't try to allocate memory-using malloc and deallocate with delete operator and vice versa. But, we use both malloc and new in single program (Refer Stroustrup style and Technique FAQ Page)

In C++ new operator is used to allocate the memory.

For example, allocate the memory for integer,

// allocate memory using new operator
Int *var = new int;
 
//deallocates memory using delete operator
delete var; 
 

The programmer also allocate array of memory using new operator. For example,

// Allocate 100 integer elements
Int *a= new int[100];
 
//delete the array of elements
delete [] a; 
 

What is difference between Int a; and int *a = new int. If we use int a, the variable is allocated memory space and deallocated when it goes out of scope. But, if we use second method the programmer explicitly mentions the delete operator to delete the variable in the memory.

The heap allocation is a portion of memory reserved for a program to use for the temporary storage. The heap allocation size cannot be known until the program is running. Stack is a region of reserved memory in which programs store status data. This status data maybe procedure and function addresses, parameters or local variables.

The C++ is a object oriented programming language. So, it supports polymorphism, encapsulation, data abstraction and inheritance and more. C++ provides programmers special member function constructor and destructor with in class definition. The contractor and destructor are the special member function to initialize the data in constructor and deallocate data from destructor.

MFC Memory Management:

MFC Support two types of memory management. Frame allocation and Heap allocation. The frame allocation objects automatically deleted when it goes out of scope. But, in the heap allocation the programmer deletes the object by using delete operator explicitly.

Frame allocation allocates object within scope. Frame variables are like automatic variable. Automatic variable is the variable is only available within the function or body in the braces. For example,

Void Myfunction()
{
    // local variable
    int nVariable1, nVraiable2;
    float fVariable;
 
    // automatically destroy when it goes out of scope
 
}
 

in function Myfunction contains the nVariable1, nVariable2 and fVariable. These variables are accessed only within the function. If we try to access out of this function, the compiler gives on error message.

The only advantage in automatic memory management, the programmer doesn't concentrate on memory deal location. The frame allocation uses in the stack. The stack is the temporarily store data in local scope.

MFC heap allocation uses to allocate memory using new operator and delete use delete operator. The objects lifetime is controlled by the programmer. If programmer doesn't remember to deallocate memory the memory leak problem occurs. So, programmer handles memory carefully. For example, heap allocation,

Void Display()
{
// allocate memory space use new operator

CMyClass *objClass = new CmyClass();
ObjClass->MyFunction();

// delete the Object
delete ObjClass;
}

So, the programmer deletes explicitly object class.

MFC provides CMemoryState class for detecting the memory leak. CMemoryState has no base class. It is used to detect the memory leak in MFC based programs. CMemoryState is available for only debug version only. The CMemoryState contains the afx.h header file. We use the CMemoryState within the #if defined (_DEBUG) and #endif Macro. Because, the CMemoryState uses debug mode only.

CMemoryState provides the functions to check the memory state and see the difference between the checkpoints. The following example is to find the difference in memory leak.

//declare the object
CMemoryState msOld,msnew, diffMemState;

#if defined (_DEBUG) 
    msOld.Checkpoint();
    CMyClass* obj = new CMyClass();
    msnew.Checkpoint();
#endif 


#if defined (_DEBUG) 
    if( diffMemState.Difference(msOld, msnew) )
    {
           TRACE( "Memory leaked!\n" );
           diffMemState.DumpStatistics();
    }
#endif

Microsoft suggests don't use to realloc for resize the memory. If you try to allocate object use new and reallocate object-using realloc the result will be corrupted in debug version in MFC.

Conclusion:

The memory management is a complex field. I explained the fundamental concepts in memory management in C/C++ and MFC. I didn't explain the more complex details in memory management and Win32 memory management. The .Net enabled languages use garbage collection techniques. So, the memory management is done automatically.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

R.selvam
Software Developer (Senior)
India India
Selvam has worked on several technologies like Core Java, VC++, MFC, Windows API and Weblogic server. He takes a lot of interest in reading technical articles and enjoy writing them too. He has been awarded as a Microsoft Community Star in 2004, MVP in 2005-06, SCJP 5.0 in 2009, Microsoft Community Contributor(MCC) 2011.
 
Github : https://github.com/selvamselvam
Web site: http://www15.brinkster.com/selvamselvam
Follow on   LinkedIn

Comments and Discussions

 
Generalbig buffer Pinmemberali khalilvand29-Sep-04 3:45 
GeneralRe: big buffer PinsussPraveen Gaur6-Oct-04 20:09 
GeneralRe: big buffer PinmemberDavid Nash23-Mar-05 21:43 
GeneralRe: big buffer PinsussPraveen Gaur16-Apr-05 7:20 
GeneralRe: big buffer PinsussAnonymous17-Aug-05 7:36 
GeneralWhy the first circle has the memory leak Pinmemberftai1-Jun-04 14:26 
GeneralRe: Why the first circle has the memory leak PinmemberDavid Nash23-Mar-05 20:31 
GeneralRe: Why the first circle has the memory leak Pinmembervenkyhyd12-May-05 21:02 
General"Complex"? I think not. Pinmemberarmentage3-May-04 8:28 
GeneralRe: "Complex"? I think not. [modified] PinmemberR.selvam7-May-04 3:06 
GeneralRe: "Complex"? I think not. Pinmemberarmentage7-May-04 5:38 
GeneralRe: "Complex"? I think not. PinmemberSamuel Gonzalo26-May-04 1:39 
GeneralRe: "Complex"? I think not. Pinmemberftai1-Jun-04 13:44 
GeneralRe: "Complex"? I think not. PinmemberVadik B21-Sep-06 9:36 
GeneralRe: "Complex"? I think not. PinmemberMember 89347617-May-12 21:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 3 May 2004
Article Copyright 2004 by R.selvam
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid