Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak

Similar documents
Project. C++: Smart Pointers. The Plan. Announcement. Memory Leak. Pointer Ownership. Today: STL 1 Wednesday: STL 2 Thursday: Smart Pointers

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

Pointers. Developed By Ms. K.M.Sanghavi

COMP6771 Advanced C++ Programming

Common Misunderstandings from Exam 1 Material

Smart Pointers. Some slides from Internet

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Smart Pointers - What, Why, Which?

ALL ABOUT POINTERS C/C++ POINTERS

Object-Oriented Programming for Scientific Computing

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

CS 241 Honors Memory

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

CPSC 427: Object-Oriented Programming

RAII and Smart Pointers. Ali Malik

Smart Pointers in C++11

CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers

Dynamic Memory Management! Goals of this Lecture!

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

04-17 Discussion Notes

CA31-1K DIS. Pointers. TA: You Lu

Consider the program...

Short Notes of CS201

CS 11 C track: lecture 5

Implementing Abstractions

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

CS201 - Introduction to Programming Glossary By

COMP 2355 Introduction to Systems Programming

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

Intermediate Programming, Spring 2017*

CSCI-1200 Data Structures Spring 2017 Lecture 27 Garbage Collection & Smart Pointers

COSC Software Engineering. Lecture 16: Managing Memory Managers

Copy Control 2008/04/08. Programming Research Laboratory Seoul National University

Discussion Week 1. TA: Kyle Dewey. Sunday, September 25, 11

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

Announcements. Lecture 04b Header Classes. Review (again) Comments on PA1 & PA2. Warning about Arrays. Arrays 9/15/17

CS201 Some Important Definitions

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

Dynamic Memory Management

Pointers, Dynamic Data, and Reference Types

Vector and Free Store (Pointers and Memory Allocation)

TI2725-C, C programming lab, course

CSC 1600 Memory Layout for Unix Processes"

CSI33 Data Structures

In Java we have the keyword null, which is the value of an uninitialized reference type


CS24 Week 3 Lecture 1

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

C How to Program, 6/e, 7/e

CS32 - Week 1. Umut Oztok. June 24, Umut Oztok CS32 - Week 1

Vector and Free Store (Vectors and Arrays)

DAY 3. CS3600, Northeastern University. Alan Mislove

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

Class Destructors constant member functions

Pointers! Arizona State University 1

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

Mobile Application Development

C11: Garbage Collection and Constructors

Memory Management in C (Dynamic Strings) Personal Software Engineering

CSE 333 Lecture smart pointers

CMSC 330: Organization of Programming Languages. Ownership, References, and Lifetimes in Rust

StackVsHeap SPL/2010 SPL/20

Assignment of Structs

CPSC 427: Object-Oriented Programming

G Programming Languages - Fall 2012

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

Ch. 11: References & the Copy-Constructor. - continued -

Ch. 12: Operator Overloading

21. Dynamic Datatypes and Memory Management

Dynamic Memory Management

Constants, References

the gamedesigninitiative at cornell university Lecture 10 Memory Management

Chapter 13: Copy Control. Overview. Overview. Overview

Exception Safety. CS 311 Data Structures and Algorithms Lecture Slides Wednesday, October 28, Glenn G. Chappell. continued

Assertions and Exceptions

Exception Safe Coding

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

6.096 Introduction to C++ January (IAP) 2009

Chapter 17 vector and Free Store

C++ Programming. Pointers and Memory Management. M1 Math Michail Lampis

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Kurt Schmidt. October 30, 2018

The University of Nottingham

CPSC 213. Introduction to Computer Systems. Instance Variables and Dynamic Allocation. Unit 1c

Copy Constructors and Assignment Operators

A Crash Course in (Some of) Modern C++

CS61C : Machine Structures

Dynamic Allocation of Memory

Dynamic Allocation in C

GEA 2017, Week 4. February 21, 2017

Engineering Robust Server Software

21. Dynamic Datatypes and Memory Management

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

Introducing C++ to Java Programmers

Transcription:

Memory Leak C++ Memory Problems or When Good Memory Goes Bad A bug in a program that prevents it from freeing up memory that it no longer needs. As a result, the program grabs more and more memory until it finally crashes because there is no more memory left. In short Allocating without cleaning up. Memory Leak class Foo private int *array_member; int asize; public Foo (int size); ~Foo (); Memory Leak FooFoo (int size) asize (size), array_member (new int[size]) for (int i=0; i<size; i++) array_member[i] = 0; void f () // local aclass object aclass a (20); Memory Leak aclass a asize array_member 20 ints Everything that is a pointer should be owned Responsible for cleanup when finished Should be known to programmer Should be by design during implementation. stack Owner and only owner should perform a delete. heap

Class members If you allocate it during construction, you should deallocate during destruction. Should also deallocate during Copy construction operator= // constructor FooFoo (int size) asize (size), array_member (new int[size]) for (int i=0; i<size; i++) array_member[i] = 0; // destructor Foo~Foo () delete [] array_member; // copy constructor FooFoo (const Foo &F) if (F!= (*this) delete [] array_member; array_member = new int[f.asize]; asize = F.asize; for (int i=0; i<asize; i++) array_member[i] = F.array_member[i]; // assignment operator Foo &Foooperator= (const Foo &F) if (F!= (*this) delete [] array_member; array_member = new int[f.asize]; asize = F.asize; for (int i=0; i<asize; i++) array_member[i] = F.array_member[i]; return (*this); Pointers returned by functions Who should be responsible for memory to which these pointers point? class Moo private char* myid static char anotherid[15]; public Moo (); char *getid();

Allocation done in method caller should be responsible for pointer. char *id = new char[15]; strcpy (id, I am a cow ); return id; Allocation done in constructor object should be responsible for pointer.should deallocate in destructor MooMoo () myid (new char[15]) strcpy (id, I am a cow ); return myid; Memory is static object should be responsible for pointer but no deallocation necessary char MooanotherID[15] = I am a cow ; return anotherid; Memory is static object should be responsible for pointer but no deallocation necessary // This is okay too. static char idinfunct[50] = I am a cow ; return idinfunct; Should not return pointer to local variable // This is not okay. char idinfunct[50] = I am a cow ; return idinfunct; Pointers returned by functions Who should be responsible for memory to which these pointers point? Either caller or object Should be clearly designed and documented

Anonymous Objects An anonymous object is an object in every sense except that it has no name. Used for creating very temporary objects. Point square[] = Point(0,0),Point(0,1),Point(1,1),Point(1,0) ; Anonymous Objects Beware when anonymous objects are allocated on free store. vector< Card * > hand; hand.push_back( new Card() ); hand.push_back( new Card() ); hand.push_back( new Card() ); If vector does not take ownership of the objects stored in it, a memory leak is possible. Questions? Memory Leak / Pointer Ownership Dangling Pointers Pointer is pointing to something that it shouldn t be. Can happen if If the scope of a pointer extends beyond that of the object being pointed to i.e Returning a pointer to a local variable. If a dynamically allocated memory cell is freed explicitly and then the pointer pointing to such a space is used in subsequent code. Dangling Pointers p1 = new Foo; delete p1; p2 = new Bar; // What if same memory is //given to p2? int i = p1->data; // i contains garbage p1->op(); // p2's object mysteriously changes! Dangling Pointers Ways to prevent dangling pointers Do not return pointers to local variables. After calling delete on a pointer, immediately set it to NULL. p1 = new Foo; delete p1; p1 = 0; p2 = new Bar; p1->op(); // core dump!

Recall that C++ has no array bounds checking. Writing past bounds of array will trash unsuspecting memory. int *a = new int[20]; aclass *b = new aclass(); a[20] = 23; // b mysteriously // changes a b heap This can be quite dangerous for local arrays int a[20]; a[20] = 23; a Local Variables Local Variables Return Address Function Arguments Return Address Function Arguments char a[20]; strcpy (a, This string is too long ); Dangling Pointers / Overwriting Arrays Questions?

Getting around these problems The smart pointer Prevents memory leaks and dangling pointers Wrapper class that owns a pointer to an object Object keeps a reference count of variables accessing it When the reference count reaches 0, the object is deleted by the smart pointer. After deleting object, pointer value set to 0. Smart pointer ptr The Smart Pointer The Smart Pointer Using smart pointers The smart pointer should look and act like a regular pointer Should support -> Should support * Should be smarter than your average pointer. Reduce memory leaks Reduce dangling pointers Take ownership Instead of MyClass* p(new MyClass); p->dosomething(); delete p; Use SmartPtr<MyClass> p(new MyClass); p->dosomething(); p will cleanup after itself Smart Pointers We will be looking at the details of a smart pointer in Week 10 There is a Smart Pointer class available for use on the project See choices.html of of Project pages Questions?