dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Home » Tip Bank » C++
Language: C
Expertise: Intermediate
Feb 9, 2004

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Release All Resources Before Exiting a Function

This code snippet releases memory and closes all open handles, files, etc. before exiting a function. Even if a function has to return, for whatever reason, this code ensures all resources remain released.

The code, which is written in a function, is written in the __try & __finally block.

Here is small example:


#define MYCONSTANT "OK THIS IS A TEST"

bool function()
{
    int a = 0;
    char* ptrMem = new char[51];
    strcpy(ptrMem, MYCONSTANT);
    __try
    {
       printf("Enter a number : - ");
       scanf("%d",&a);
       fflush(stdin);
       if(0 == (a%2))
       {
           //some problem, required to quit
           return false;
       }
       else
       {
           //No problem do the required operations
           //and delete the memory
         }
    }
   __finally
   {
         if(NULL != ptrMem)
          {
               delete [] ptrMem;
               ptrMem = NULL;
          }
   }
 }
The __try and __finally blocks take care that at any time the function returns, it deallocates the allocated memory. This block is very important, for releasing all the allocated resources, hence making sure that all the resources are properly deallocated&—meaning, no more memory leaks, open handles, etc.
Kedar Babar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date