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

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

Memory Leak? C++ unmanaged. Simple code.

Not familiar with unmanaged C++. Wondering if this following simple code is acceptable, or does it contain a memory leak. When does tstr get deallocated?
std::string FormatHelper::PadTo(std::string s, const size_t num, const char paddingChar)
{
  std::string tstr = s;
  if(num > tstr.size()) { tstr.insert(0, num - tstr.size(), paddingChar); }
  return tstr;
}

Open in new window

0
deleyd
Asked:
deleyd
1 Solution
 
mrwad99Commented:
a) The local tstr is constructed from 's'
b) Because it is returned as a copy (i.e. not a reference or a pointer), a copy of tstr is made.  This copy is returned to the caller of FormatHelper::PadTo().  At this point we have two identical variables
c) The local tstr we constructed on line 3 is then destroyed when the function FormatHelper::PadTo() exits.

Now, in the caller of FormatHelper::PadTo(), if the string returned (tstr copy) is assigned to a stack allocated object, it will be destroyed when it goes out of scope.  If it is assigned to a heap allocated variable, it will only be destroyed via a call to delete.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

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