Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Memory Leak? C++ unmanaged. Simple code.

Posted on 2013-12-27
1
Medium Priority
?
388 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 1000 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

715 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