Solved

Memory Leak? C++ unmanaged. Simple code.

Posted on 2013-12-27
1
374 Views
Last Modified: 2013-12-28
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
Comment
Question by:deleyd
1 Comment
 
LVL 19

Accepted Solution

by:
mrwad99 earned 250 total points
ID: 39743673
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now