Solved

Memory Leak? C++ unmanaged. Simple code.

Posted on 2013-12-27
1
371 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

757 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

23 Experts available now in Live!

Get 1:1 Help Now