473,327 Members | 1,979 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

where to add the delete statement in try and catch?

I have the following function and there is memory leak as there is no "delete" for the corresponding "new". I am confused where to add delete. Kindly let me know where all to add the delete statement?

Expand|Select|Wrap|Line Numbers
  1. int  IsSwapClearable ( const sTRADE* pSummitTrade )
  2. {
  3. cout<<"INSIDE IsSwapClearable()"<<endl;
  4.    try
  5.    {
  6.       int retval = sFALSE;
  7.  
  8.       CheckSwapClear* mySwapClearChecks = new CheckSwapClear();
  9.  
  10.       // must be a mapped counterparty so do not call IsSwapClearCounterparty();
  11.  
  12.       if ( mySwapClearChecks->IsSwapClearMappedCounterparty ( pSummitTrade->Base
  13. .Env->Cust.Name ) == sTRUE )
  14.       {
  15.          switch ( pSummitTrade->Base.TradeType )
  16.          {
  17.             case sTT_SWAP :
  18.                  retval = mySwapClearChecks->IsSwapClearableSwap ( pSummitTrade
  19. );
  20.                  break;
  21.             default :
  22.                  break;
  23.          }
  24.       }
  25.       return retval;
  26.    }
  27.    catch( DmgException& aExcep )
  28.    {
  29.       mLogMessage ( "EXCEPTION caught in IsSwapClearable()" );
  30.  
  31.       throw;
  32.    }
  33.    catch ( ... )
  34.    {
  35.       mLogMessage ( "Unknown Exceptions caught in IsSwapClearable()" );
  36.  
  37.       throw;
  38.    }
  39. }
  40.  
  41. And the destructor is defined as below:
  42.  
  43. CheckSwapClear::~CheckSwapClear()
  44. {
  45.    try
  46.    {
  47.    }
  48.    catch( DmgException& aExcep )
  49.    {
  50.       aExcep.ReThrowGpo("CheckSwapClear::~CheckSwapClear()", sSERIOUS );
  51.    }
  52.    catch ( ... )
  53.    {
  54.       DmgException::ThrowGpo( "CheckSwapClear::~CheckSwapClear() : Unknown Excep
  55. tion", sSERIOUS );
  56.    }
  57. }
Kind Regards,
Rasmi.
Aug 14 '07 #1
7 4790
Any reply from anyone please.

Thanks,
Aug 14 '07 #2
oler1s
671 Expert 512MB
You've made two grevious mistakes in your conduct. You bumped a thread within the span of four hours. And your post is unreadable because you failed to use CODE tags. Read the posting guidelines. You can acknowledge that you have done so by marking up your posted code with the appropriate tags.

You delete dynamically allocated objects where you can guarantee code flow. For example, in a try/catch block, the catch part is not guaranteed. It only runs when there is an exception. A very bad hack would be to force an exception at the end by doing a throw 1, and then deleting the resource in a catch block. But that's not what you should be doing.

If you can figure out where you know the code will definitely flow, and it is valid to release the resource (is this true of right after the try/catch block?), that's where you put the delete. I normally try to avoid these kind of naked resources. Look up RAII and auto_ptr. See http://www.gotw.ca/publications/using_auto_ptr_effectively.htm and the wikipedia article on RAII (as well as Google).
Aug 14 '07 #3
weaknessforcats
9,208 Expert Mod 8TB
The try block is very poorly designed. Your pointer is inaccessible after the try block so you have a very large try block. Don't do that. Do this instead:

Expand|Select|Wrap|Line Numbers
  1. int IsSwapClearable ( const sTRADE* pSummitTrade )
  2. {
  3. cout<<"INSIDE IsSwapClearable()"<<endl;
  4. CheckSwapClear* mySwapClearChecks = 0;
  5. int retval = sFALSE;
  6.  
  7. try
  8. {
  9.  
  10.    mySwapClearChecks = new CheckSwapClear();
  11. }
  12. catch (etc...)
  13. {
  14.      delete mySwapClearChecks;
  15. }
  16.  
  17. // must be a mapped counterparty so do not call IsSwapClearCounterparty();
  18.  
  19. if ( mySwapClearChecks->IsSwapClearMappedCounterparty ( pSummitTrade->Base
  20. .Env->Cust.Name ) == sTRUE )
  21. {
  22. switch ( pSummitTrade->Base.TradeType )
  23. {
  24. etc...
  25.  
Remember that any exception thrown in this code does not unwind the new allocation. To do that, you would need to delete the allocation in the catch block.
Aug 14 '07 #4
RRick
463 Expert 256MB
The general rule is that you must delete the object at every exit point. In your method, you have 2 exits from exceptions and one normal exit. You have to account for all of them.

Also, forget about putting a try/catch block in the destructor. Since your try block has nothing in it, it's not going to catch anything. Remember, try/catch blocks can be nested. If your idea is to catch an exception from the calling method in the destructor, this isn't going to work.
Aug 14 '07 #5
Question: Why do you use dynamical memory allocation at all? Just type
Expand|Select|Wrap|Line Numbers
  1. CheckSwapClear mySwapClearChecks;
The compiler will free the memory automatically when leaving IsSwapClearable.
Generally: Only use "new" if you need a variable outside of the block where it is allocated. Even then it might be better to copy the variable into another allocated on the stack instead on the heap. Saves you alot of trouble
Aug 15 '07 #6
weaknessforcats
9,208 Expert Mod 8TB
Question: Why do you use dynamical memory allocation at all? Just type
Code: ( text )
CheckSwapClear mySwapClearChecks;
When the function completes, mySwaoClearChecks is destroyed. That means you can't usee it any other function. That means your entire program must be in one function. That means you can never reuse any of your code without making copies of it. Actually, this was how you did things before 1972.

Defining the object on the stack may not work as stack memory is limited and you may run out of it before you have all the variables created.

I suppose you could make everything global but then global memory is limited. Using global variables is the same as using one giant function for the entire program.

But the worst thing is that the size of the object must be known at compile time. If you have a name field that could vary from 3 to 150 characters, you will need to make all names 150 characters to avoid possible program faulires.

Even worse than worst, the kind of object to create must bne known at compile time. That means you can't create an object based on user inoput when the program is running. Bascially, you can't write either an object-based or an object-oriented program.

So, you have to go exactly in the opposite direction: You never use the stack for objects passing between functions or for objects that can't be created at compile time. Instead, you use handles (not pointers). There is an article on handles in the C/C++ Articles forum that sshows you how to do this.
Aug 15 '07 #7
Thanks a lot to all of you. Now I could able to successfully write my code. Thanks.
Aug 16 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: mttc | last post by:
I read articles that suggest preventing delete by throwing Exception from RowDeleting Event. I not understand where I can catch this Error?
12
by: Lucas Tam | last post by:
I have a very simple loop: If (Directory.Exists(tempDirectory)) Then Try Dim Files() As String = Directory.GetFiles(tempDirectory) 'Clear out directory For Each Filename As String In Files...
6
by: Lighter | last post by:
Big Problem! How to overload operator delete? According to C++ standard, "A deallocation function can have more than one parameter."(see 3.7.3.2); however, I don't know how to use an overloaded...
5
by: Neven Klofuar | last post by:
hi, I have a problem when trying to delete a file. I have to extract some information from a file, and then I have to delete it. When I try to delete it after I read it, I get a "Access...
7
by: Chris | last post by:
Hello all... I have a program with the following structure (all classes mentioned are of my own creation, and none of the classes contain try or catch blocks): - main() consists of a large...
12
by: yufufi | last post by:
Hello, How does delete know how much memory to deallocate from the given pointer? AFAIK this informations is put there by new. new puts the size of the allocated memory before the just before...
9
by: =?Utf-8?B?TWlrZQ==?= | last post by:
Hi. I have a class with an collection property. The collection property is sometimes equal to nothing. The class has a function named 'Exists' which returns TRUE if the specified string exists...
7
by: ITAutobot25 | last post by:
My delete button is not working in my GUI and my due date is today before midnight. Can anyone show me how to correct this error? My assignment statement is below as well as 5 classes. InventoryGUI...
12
by: vidishasharma | last post by:
Hi, I want to get the location which user selects for installaion of program using msi installer. I require this to do kind of cleanup activity if something goes wrong with the installation. ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.