473,378 Members | 1,152 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,378 software developers and data experts.

Using 'delete' and its effect on local and variables being passed

I have a function

Expand|Select|Wrap|Line Numbers
  1. void AddItem(char* buffer, char* items[], int& index)
  2. {
  3.    char* temp = new char[strlen(buffer) + 1];
  4.  
  5.    strcpy(temp, buffer);
  6.  
  7.    items[index] = temp;
  8.  
  9.    index++;
  10. }
  11.  
Here we are allocating memory space for temp using new.
But we are not deleting it.
The varible temp is not used anywhere outside the function.
But buffer and index are being used.
Should I use delete here for temp or not?
Please let me know.
Thanks in advance.
Jul 25 '07 #1
10 2004
Banfa
9,065 Expert Mod 8TB
Here we are allocating memory space for temp using new.
But we are not deleting it.
The varible temp is not used anywhere outside the function.
But buffer and index are being used.
Should I use delete here for temp or not?
The pointer to the buffer stored in temp is copied to Items, therefore the pointer is not lost, not deleting it here is not intrinsically a problem (it may of course be a problem in the context of the rest of the program).
Jul 25 '07 #2
ravenspoint
111 100+
The variable temp is an automatic, which means it is automatically deleted when the routine exits.

If you are asking about freeing the memory allocated in the routine ( and pointed to by temp ) you cannot do that until you are finished using the memory. It will not be freed automatically, so you have to look after that chore somewhere - or exit the program.
Jul 25 '07 #3
weaknessforcats
9,208 Expert Mod 8TB
If you are asking about freeing the memory allocated in the routine ( and pointed to by temp ) you cannot do that until you are finished using the memory. It will not be freed automatically, so you have to look after that chore somewhere - or exit the program.
To rasmidas:

You cannot tell from a pointer whether it is safe to delete it. The only time it is safe is when there are no other copies of it anywhere else in the program. You might read the article on Handle Classes in the C/C++ Articles forum. These are the smart pointers that are often used to control safe ddeleting of pointers.
Jul 25 '07 #4
sicarie
4,677 Expert Mod 4TB
Just FYI - I changed the title of the thread to better describe the issue.
Jul 25 '07 #5
This temp is a local pointer variable and is not being used anywhere else in the program. However buffer, index and items are being used in the program. If I will use
delete temp;
at the end of this function, that is if I will write as below:
void AddItem(char* buffer, char* items[], int& index)
{
char* temp = new char[strlen(buffer) + 1];

strcpy(temp, buffer);

items[index] = temp;

index++;

delete temp;
}

will it affect the program or it will be correct after adding delete statement.
Thanks in advance.
Jul 26 '07 #6
gpraghuram
1,275 Expert 1GB
This temp is a local pointer variable and is not being used anywhere else in the program. However buffer, index and items are being used in the program. If I will use
delete temp;
at the end of this function, that is if I will write as below:
void AddItem(char* buffer, char* items[], int& index)
{
char* temp = new char[strlen(buffer) + 1];

strcpy(temp, buffer);

items[index] = temp;

index++;

delete temp;
}

will it affect the program or it will be correct after adding delete statement.
Thanks in advance.
Hi
If you delete the temp then the item will be referring to an invalid memoy location.
You should delete this memory when you dont need item like delete item[i];

Raghuram
Jul 26 '07 #7
Thanks all. Now I am clear. Thanks a lot.
Jul 26 '07 #8
Here I am pasting the function where I am calling the above AddItem() function.

Expand|Select|Wrap|Line Numbers
  1. int PopulateClearing ( sDOC_SOURCE* DocSource, char* items[], int& index )
  2. {
  3.    char buffer[128] = "";
  4.    char msg[199] = "";
  5.  
  6.    RWCString swiftFlag = "N";
  7.    RWCString clearingSys = "";
  8.    RWCString newSwift = "Y";
  9.  
  10.    int swiftCount = 1;
  11.  
  12.    if ( DocSource->Function == sDF_INCEPTION )
  13.    {
  14.       // sprintf ( msg, "Entered PopulateClearing() for trade '%s'",
  15.       //                DocSource->Trade.Base.TradeID.Num );
  16.       // mLogMessage ( msg );
  17.  
  18.       try
  19.       {
  20.          if ( IsSwiftable ( &(DocSource->Trade) ) == sTRUE )
  21.          {
  22.               swiftFlag = "Y";
  23.  
  24.               if ( IsSwapClearable ( &DocSource->Trade ) == sTRUE )
  25.               {
  26.                  clearingSys = "SWAPCLEAR";
  27.               }
  28.  
  29.          }
  30.          if ( ( swiftFlag == "Y" ) ||
  31.               ( sTT_FRA == DocSource->Trade.Base.TradeType ) )
  32.          {
  33.             sENTITY* pEntity = sGetEntityByName( "cSWIFTREC" );
  34.             cSWIFTREC* pSwiftRec = NULL;
  35.  
  36.             if ( sEntityCreate( pEntity, (void**)&pSwiftRec ) != sSUCCESS )
  37.             {
  38.                mLogMessage( "Error creating cSWIFTREC entity" );
  39.             }
  40.             else
  41.             {
  42.                strcpy( pSwiftRec->TradeId.Num, DocSource->Trade.Base.TradeID.Num );
  43.                pSwiftRec->TradeType = DocSource->Trade.Base.TradeType;
  44.  
  45.                if ( sEntityDBRead( pEntity, pSwiftRec, "EQUAL", 00 ) == sSUCCESS )
  46.                {
  47.                   newSwift = "N";
  48.                   swiftCount = ++pSwiftRec->SwiftCount;
  49.                }
  50.             }
  51.          }
  52. /
  53.                   newSwift = "N";
  54.                   swiftCount = ++pSwiftRec->SwiftCount;
  55.                }
  56.             }
  57.          }
  58.       }
  59.       catch ( ... )
  60.       {
  61.          mLogMessage ( "Exception in PopulateClearing() caught :" );
  62.          mLogMessage ( "  IsSwiftable reset to 'N' in the BLOB" );
  63.          mLogMessage ( "  ClearingSystem reset to '' in the BLOB" );
  64.          swiftFlag = "N";
  65.          clearingSys = "";
  66.       }
  67.  
  68.  
  69.       // sprintf ( msg, "BLOB field 'IsSwiftable' set to '%s' for trade '%s'",
  70.       //                swiftFlag.data(), DocSource->Trade.Base.TradeID.Num );
  71.       // mLogMessage ( msg );
  72.  
  73.       // sprintf ( msg, "BLOB field 'ClearingSystem' set to '%s' for trade '%s'",
  74.       //                clearingSys.data(), DocSource->Trade.Base.TradeID.Num );
  75.       // mLogMessage ( msg );
  76.  
  77.  
  78.       sprintf ( buffer, "IsSwiftable=\"%s\";\n", swiftFlag.data() );
  79.       AddItem(buffer, items, index);
  80.  
  81.       sprintf ( buffer, "ClearingSystem=\"%s\";\n", clearingSys.data() );
  82.       AddItem(buffer, items, index);
  83.  
  84.       sprintf ( buffer, "NewSwift=\"%s\";\n", newSwift.data() );
  85.       AddItem(buffer, items, index);
  86.  
  87.       sprintf ( buffer, "SwiftCount=\"%d\";\n", swiftCount );
  88.       AddItem(buffer, items, index);
  89.  
  90.    }
  91.  
  92.  
  93.    return sSUCCESS;
  94. }
  95.  
Please let me know how and where to delete the memory allocated to temp.
Thanks in advance.
Jul 27 '07 #9
gpraghuram
1,275 Expert 1GB
Here I am pasting the function where I am calling the above AddItem() function.

Expand|Select|Wrap|Line Numbers
  1. int PopulateClearing ( sDOC_SOURCE* DocSource, char* items[], int& index )
  2. {
  3.    char buffer[128] = "";
  4.    char msg[199] = "";
  5.  
  6.    RWCString swiftFlag = "N";
  7.    RWCString clearingSys = "";
  8.    RWCString newSwift = "Y";
  9.  
  10.    int swiftCount = 1;
  11.  
  12.    if ( DocSource->Function == sDF_INCEPTION )
  13.    {
  14.       // sprintf ( msg, "Entered PopulateClearing() for trade '%s'",
  15.       //                DocSource->Trade.Base.TradeID.Num );
  16.       // mLogMessage ( msg );
  17.  
  18.       try
  19.       {
  20.          if ( IsSwiftable ( &(DocSource->Trade) ) == sTRUE )
  21.          {
  22.               swiftFlag = "Y";
  23.  
  24.               if ( IsSwapClearable ( &DocSource->Trade ) == sTRUE )
  25.               {
  26.                  clearingSys = "SWAPCLEAR";
  27.               }
  28.  
  29.          }
  30.          if ( ( swiftFlag == "Y" ) ||
  31.               ( sTT_FRA == DocSource->Trade.Base.TradeType ) )
  32.          {
  33.             sENTITY* pEntity = sGetEntityByName( "cSWIFTREC" );
  34.             cSWIFTREC* pSwiftRec = NULL;
  35.  
  36.             if ( sEntityCreate( pEntity, (void**)&pSwiftRec ) != sSUCCESS )
  37.             {
  38.                mLogMessage( "Error creating cSWIFTREC entity" );
  39.             }
  40.             else
  41.             {
  42.                strcpy( pSwiftRec->TradeId.Num, DocSource->Trade.Base.TradeID.Num );
  43.                pSwiftRec->TradeType = DocSource->Trade.Base.TradeType;
  44.  
  45.                if ( sEntityDBRead( pEntity, pSwiftRec, "EQUAL", 00 ) == sSUCCESS )
  46.                {
  47.                   newSwift = "N";
  48.                   swiftCount = ++pSwiftRec->SwiftCount;
  49.                }
  50.             }
  51.          }
  52. /
  53.                   newSwift = "N";
  54.                   swiftCount = ++pSwiftRec->SwiftCount;
  55.                }
  56.             }
  57.          }
  58.       }
  59.       catch ( ... )
  60.       {
  61.          mLogMessage ( "Exception in PopulateClearing() caught :" );
  62.          mLogMessage ( "  IsSwiftable reset to 'N' in the BLOB" );
  63.          mLogMessage ( "  ClearingSystem reset to '' in the BLOB" );
  64.          swiftFlag = "N";
  65.          clearingSys = "";
  66.       }
  67.  
  68.  
  69.       // sprintf ( msg, "BLOB field 'IsSwiftable' set to '%s' for trade '%s'",
  70.       //                swiftFlag.data(), DocSource->Trade.Base.TradeID.Num );
  71.       // mLogMessage ( msg );
  72.  
  73.       // sprintf ( msg, "BLOB field 'ClearingSystem' set to '%s' for trade '%s'",
  74.       //                clearingSys.data(), DocSource->Trade.Base.TradeID.Num );
  75.       // mLogMessage ( msg );
  76.  
  77.  
  78.       sprintf ( buffer, "IsSwiftable=\"%s\";\n", swiftFlag.data() );
  79.       AddItem(buffer, items, index);
  80.  
  81.       sprintf ( buffer, "ClearingSystem=\"%s\";\n", clearingSys.data() );
  82.       AddItem(buffer, items, index);
  83.  
  84.       sprintf ( buffer, "NewSwift=\"%s\";\n", newSwift.data() );
  85.       AddItem(buffer, items, index);
  86.  
  87.       sprintf ( buffer, "SwiftCount=\"%d\";\n", swiftCount );
  88.       AddItem(buffer, items, index);
  89.  
  90.    }
  91.  
  92.  
  93.    return sSUCCESS;
  94. }
  95.  
Please let me know how and where to delete the memory allocated to temp.
Thanks in advance.

HI,
Since the logic is yours you shuld in a better position to tell where to put the delete function.

Raghuram
Jul 27 '07 #10
weaknessforcats
9,208 Expert Mod 8TB
Please let me know how and where to delete the memory allocated to temp.
It's never safe to delete temp. That's because the address of temp has been copied into another array.

It you could only know that the temp you want to delete does not exist anywhere else in the program, then you could delete it.

You need a smart pointer.

Read the article on Handle classes the C/C++ Articles forum. In that article is a template for a smart pointer that you can copy into your own code and start using.

As a rule, the single most dangerous thing you can do in a C++ program is to pass pointers around. When you do, you have to ensure that the objects pointed at are still there.
Jul 27 '07 #11

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

Similar topics

7
by: Gary | last post by:
I haver a table of students - Say 100 students that I need to be able to update/delete and amend. I know I can do this one student at a time which is simple but lets say I want to see all the...
2
by: Eric | last post by:
Hi, I'm used to C/C++ where if you "new" something you really need to "delete" it later. Is that also true in javascript? if i do "mydate = new date();" in a function and dont "delete mydate" when...
8
by: pertheli | last post by:
I am in a situation where only "goto" seems to be the answer for my program logic where I have to retry calling some repeated functions. Can anybody help in the usage of goto and its effect in...
13
by: gary | last post by:
Hi, We all know the below codes are dangerous: { int *p = new int; delete p; delete p; } And we also know the compilers do not delete p if p==NULL. So why compilers do not "p = NULL"...
4
by: banz | last post by:
Hello I have a problem to resolve: I wrote a Perlscript which caches data from a server (local on my machine) I would like to have a other connection to a remote server but I don't know how to...
10
by: feel52 | last post by:
Below you'll find the code i'm working on. It's in a button click routine and hangs after 3 or 4 sometimes 5 loops done, probably in sock.receive(....). Some code was found here( on google i mean)...
10
by: Blaxer | last post by:
There is probably a really easy way to do this, so please forgive me but I would like to set the value of a variable from a variable, an example would be... function Calculate_Something(ByVal...
65
by: Arjen | last post by:
Hi, Form a performance perspective, is it wise to use the ref statement as much as possible? Thanks! Arjen
8
by: chromis | last post by:
Hi, I'm writing a contacts section for a cms on a website, I've decided to write the section in OO code. So far I have my Contacts object and a page structure I would use for a procedural site. ...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
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...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.