Sie sind auf Seite 1von 3

Smart Pointers

Santhosh Kumar Balasa Ramnath


Electronic and Computer Engineering Department, University of Limerick Limerick, Ireland
12081752@studentmail.ul.ie Abstract In a System when an application is designed and developed its magnitude of coding and maintaining is very high. There is high probability of bugs found due to memory leaks, improper memory management, object dereferencing, and ownership semantics. The probability of bugs in the code is even higher when multi-threading applications are designed and developed. Various object oriented programming languages like Java and C# automatically provides memory management facilities like automatic deallocations of the objects and its used resources from the stack or heap memory, in other words automatic garbage collection is provided. On the other hand programming languages like C++ do not have a built-in memory management facility. This can be overcome by Smart Pointers in C++. This paper explicates the concept of Smart Pointers used in C++.

This segment is started from the lower address of the memory, so its seen to begin from the lower part of the memory layout. Once the code is entered this area of the memory cannot be increased so the area remains fixed in memory layout. Higher address

Command Line Arguments

Stack Segment

Keywords Smart Pointers, auto_ptr, Garbage collection in C++.

I. INTRODUCTION This paper introduces the challenges faced in C++ based applications; technique to solve these problems is explained in detail using one of the concepts from Object oriented design patterns [9]. Design patterns in software are reusable solutions for commonly occurring problems. Object oriented design patterns provide solutions involving classes and objects. In small scale or large scale software applications memory management plays a crucial role. Improper memory management can crash the program or application itself. Thus, memory leaks or improper memory handling can cause major bugs in the application. In C/C++ programming language the programmer has to micromanage the memory allocations and deallocations which is tedious and error-prone. In this paper we shall discuss the various memory related problems and how to solve these memory related problems with the help of Smart pointers. This paper also covers how auto_ptr i.e.., one of the Smart pointers is implemented. II. MEMORY ORGANIZATION Every program in a Computer or a system requires memory; there are four major segments in memory. They are code segment, data segment, stack segment and heap segment. Fig. 1 shows the memory layout in the system while execution. Memory Layout from [4]. A. Code Segment Code Segment is the section in memory layout where text of the program is stored. The Program Counter is used to point to this part of the memory step by step and help in execution.

Heap Segment

Uninitialized global data Initialized global data Code Segment Lower address Fig. 1. Memory Layout B. Data Segment Data Segment is the section in memory layout where the initialized global variables, non-initialized global variables and the command line arguments are stored. Command line arguments are stored in the higher address of the memory so they are seen towards the upper part of the memory layout. Both initialized and non-initialized global variables are stored in the lower addresses of the memory, so they are seen towards the lower part of the memory layout. Once the command line and other global variables are

assigned this area of the memory cannot be grown, this area remains fixed in memory layout. C. Stack Segment Stack Segment is the section in memory layout where the local variables and function return addresses are stored. Stack segment area in memory layout is not fixed, it can be grown. As the numbers of calling functions are increased, the stack grows. Local variables includes both initialized and noninitialized. These are stored at the higher address of the memory so the stack segment is seen towards the upper part of the memory layout. Stack follows FILO i.e., first in, last out structural method is used to store the data in the memory. The Stack grows towards the bottom direction in memory layout. D. Heap Segment Heap Segment is the section in memory layout where the dynamically allocated variables or objects are stored. Similar to Stack segment the heap segment area in memory layout is not fixed, depending on the dynamic allocations this section grows towards the upper direction in memory layout. Program crashes if it runs out of heap memory so proper usage of heap memory is very important. Dynamic allocations can be done using the keyword new in C++ language and dynamic de-allocations can be done using the keyword delete. Every allocated resource from heap must be deallocated after its use to ensure proper usage of the heap memory. III. MEMORY RELATED ISSUES A. Scenario1 Consider Scenario1 as the class name, and ptr is the pointer for this class created in main. Following is a scenario where de-allocation of the pointer is not done, idea from [10]:#include <iostream> #include <memory> using namespace std ;

In the above scenario memory allocated for the class pointer Scenario1 is not de-allocated after its usage by the programmer. So, this area in the heap memory is locked and is not available for other processes. If such mistakes occur very often in the program then the application will crash. B. Scenario2 Let us consider Scenario2 to be the class name and ptr to be its pointer. Following is a scenario where exception occurs in the program even before de-allocating the memory. #include <iostream> #include <memory> using namespace std ; class Scenario2{ //Body of the class void Function(){ //printing statements } }; int main(int argc, char *argv[]){ Scenario2 *ptr = new Scenario2() ; ptr->Function() ; //Exception occurs inside Funtion() delete ptr ; return EXIT_SUCCESS ; } In the above scenario if an exception occurs in Function() then the program has no chance to execute delete ptr ; command thus not de-allocating the memory from heap memory which in turn creates memory leaks in the application. These types of errors might be trivial in single threaded applications but in multi-threaded applications they cause a major damage to the software application. IV. SMART POINTERS The above discussed memory related issues can be solved with the help of try and catch exception handling facility in C++ but the overhead during the coding phase will be too high, error-prone and becomes complex to maintain the code. To overcome these problems we have a concept from object oriented design patterns known as Smart Pointers [9]. Smart pointers are nothing but a wrapper for the normal pointer, where it can perform some additional functions that normal pointers cannot, E.g.: automatically calling destructor when the execution goes out of the scope. Smart pointers are implemented using templates; auto_ptr is a smart pointer in C++ Standard library which automatically deallocates the memory when the execution goes out of the

class Scenario1{ //Body of the class void Function(){ //printing statements } }; int main(int argv, char* argv[]){ Scenario1 *ptr = new Scenario1() ; ptr->Function() ; return EXIT_SUCCESS ; }

scope. When smart pointers like auto_ptr are used, there is no need for the programmer to manually de-allocate the memory i.e.., no need to use delete keyword. Reference from [1] and [2]. auto_ptr implementation:template <class T> class auto_ptr{ public: explicit auto_ptr(T *ptr = 0):pointer(ptr){} ~auto_ptr() { delete *pointer ; } T& operator *() { return *pointer ; } T* operator ->() { return pointer ; } //Other part of the class private: T *pointer ; }; Following is an example where auto_ptr i.e.., smart pointer is used , reference from [6] [8] :#include <iostream> #include <memory> using namespace std ; class scenario{ //Body of the class void Function(){ //printing statements } }; int main(int argc, char *argv[]){ auto_ptr<scenario> scenario_ptr(new scenario()) ; scenario_ptr->Function() ; return EXIT_SUCCESS ; } In the above program there is no need to de-allocate the memory manually; the compiler itself will take care of the deallocation when auto_ptr is used. auto_ptr is defined in the header memory.h When there are exceptions and if the control goes out of scope destructor of auto_ptr is automatically initiated which does the de-allocation process. V. CONCLUSIONS Smart pointers like auto_ptr facilitate automatic garbage collection in C++. Thus smart pointers are objects which behave like pointers but perform additional functions where regular pointers cant. Smart pointers will also anticipate allocation failures, dangling pointers and other memory related issues. Also reduces the overhead to the programmers

from managing memory manually and also improves the efficiency of the application. Smart pointers enable feasibility, robustness in the program, handy in multi-threaded applications, provide proper memory consumption and help to achieve easy code maintenance. Object oriented design patterns play a pivotal role in solving some complex problems in Software. REFERENCES
[1] [2] [3] [4] [5] [6] [7] [8] [9] Bjarne Stroustup, The C++ Programming language, 3rd ed., p. 367, ISBN 978-81-317-0521-6 Nicholas A. Solter, Scott J. Kleper, Professional C++, 2011, p. 88 -89, p. 101-102, p. 424, p. 376-377, ISBN 81-265-0578-8. Garbage collection in object oriented languages. http://www.osnews.com/story/6864 Memory layout of C programs. http://www.geeksforgeeks.org/archives/14268 Smart pointers What, Why, Which? http://ootips.org/yonat/4dev/smart-pointers.html auto_ptr Class. http://msdn.microsoft.com/en-us/library/ew3fk483.aspx Smart pointers in C++. http://www.informit.com/articles/article.aspx?p=31529 Public member function std::auto_ptr. http://www.cplusplus.com/reference/std/memory/auto_ptr/auto_ptr/ Richard D. Honrung, Scott R. Khon, The use of Object-oriented design patterns in the SAMRAI Structured AMR Framework, 1998, http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.7268 Example for out of scope memory leak in C++ http://www.programmerinterview.com/index.php/c-cplusplus/what-isa-memory-leak-in-c/

[10]

Das könnte Ihnen auch gefallen