Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 946
  • Last Modified:

CStringArray memory management

The following routine manages a global CStringArray, Message.  It simply replaces the CString at the specified index in Message with the new CString, string.  My question is this - How should I correctly delete the old CString in Message which is being replaced?  Does this code completely free up the old CString when this routine is exited?  Is there a better, correct way of doing it?

CStringArray Message;

void SetMessage(short index, CString string)
{
      CString pa;

      pa = Message.GetAt(index); // get old CString
      Message.SetAt(index,string); // insert new CString
      pa.FreeExtra();
      pa.Empty(); // empty the original element at 'index'
}
0
geneo
Asked:
geneo
1 Solution
 
wpintoCommented:
Hi geneo,

You don't have to worry about memory management when it comes to CStringArray or CStrings. MFC handles it internally for you.

if you don't need the previously stored string you could rewrite the SetMessage() function as given below

void SetMessage(short index, CString string)
{
  Message.SetAt(index,string); // insert new CString
}

and it would work fine (no memory leaks)

if you wish to access the prviously stored string try
void SetMessage(short index, CString string)
{
  CString pa;
  pa = Message.GetAt(index); // get old CString
  Message.SetAt(index,string); // insert new CString
}

You don't need the following statement pa.Empty(). The CString destructor automatically frees the space.

So don't worry, use it as would use normal integer array!

Hope this helps

Wilfred
0
 
geneoAuthor Commented:
Thanks Wilfred.  I appreciate your time.  Gene.
0

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now