Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is this a memory leak?

Status
Not open for further replies.

MattWoberts

Programmer
Oct 12, 2001
156
0
0
GB
Hi all,

I'm out of practice with Visual C++, but recently had to take a look at some old code. I noticed this function which returns a date as a string:

Code:
wchar_t * MyClass::GetDate()
{
	wchar_t * sText;
	sText = new wchar_t [12];
        // Populate sText with a date....
        return sText
}

This is fine (I think). However, it gets called quite a lot, generally when building a string. It gets called like this:

Code:
basic_stringstream<wchar_t> sString;
sString << L"Some text " << class.GetDate() << L".";

Now what I noticed was that this 12 byte allocation is not being cleared up !! Am I right in thinking this will eat up more and more memory as it continues to run?

Many thanks!

Matt
 
>This is fine (I think).

No. It is ugly.

>Am I right in thinking this will eat up more and more memory as it continues to run?

Correct.

Here's how to do it
Code:
#include <string>

std::wstring MyClass::GetDate()
{
    std::wstring sText;
    // Populate sText with a date....
    return sText
}

basic_stringstream<wchar_t> sString;
sString << L"Some text " << class.GetDate().c_str() << L".";

/Per
[sub]
www.perfnurt.se[/sub]
 
Thanks for pointing me to the string class, as a C user I hadn't much experience with the STl :)

 
Code:
#include <string>

std::wstring MyClass::GetDate()
{
    std::wstring sText;
    // Populate sText with a date....
    return sText
}

basic_stringstream<wchar_t> sString;
sString << L"Some text " << class.GetDate().c_str() << L".";

Why do you think sText is not deleted before return from GetDate()? Is it not a local variable?
 
Mingis,

It is deleted in the code snippet you posted. Its in my original code snippet that sText is not deleted - and the reason is that the memory is allocated with the "new" operator, which should be explcitly "deleted".
 
My doubts were, that only pointer to previuosly deleted object is returned. But everything is ok - the whole contents of sText are copied to return value of GetDate() and then deleted once again after use. Sorry.
 
Its called return by value. If the function returned a wstring& then that would have been illegal as the wstring being referenced would have been destroyed before the reference was used. But to return an object by value is perfectly feasible tho a little expensive.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top