Solved

Memory Leak? C++ unmanaged. Simple code.

Posted on 2013-12-27
1
384 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

759 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