C++ Memory Overview 4 major memory segments Key differences from Java

Slides:



Advertisements
Similar presentations
. Smart Pointers. Memory Management u One of the major issues in writing C/C++ code is managing dynamically allocated memory u Biggest question is how.
Advertisements

CSE 332: C++ memory management idioms C++ Memory Management Idioms Idioms are reusable design techniques in a language –We’ll look at 4 important ones.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
CSE 332: C++ copy control I Copy Control (Part I) Copy control consists of 5 distinct operations –A copy constructor initializes an object by duplicating.
Informática II Prof. Dr. Gustavo Patiño MJ
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Dynamic Memory Allocation in C++. Memory Segments in C++ Memory is divided in certain segments – Code Segment Stores application code – Data Segment Holds.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles C/C++ Emery Berger and Mark Corner University of Massachusetts.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CSE 332: C++ memory management idioms C++ Memory Management Idioms Idioms are reusable design techniques in a language –We’ll look at 4 important ones.
CSE 425: Object-Oriented Programming I Object-Oriented Programming A design method as well as a programming paradigm –For example, CRC cards, noun-verb.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 Data Structures - CSCI 102 CS102 C++ Pointers & Dynamic Objects Prof Tejada.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
 Managing the heap  Resource acquisition is initialization (RAII)  Overriding operator new and delete  Class-based memory pools.
Object-Oriented Programming in C++
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 7 Pointers: Java does not have pointers. Used for dynamic memory allocation.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Writing Correct C++ Programs without “delete” Huang-Ming Huang CSE332 Guest Lecture Washington University in St. Louis.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
CSE 332: Memory management with C++ classes Memory Management with Classes Review: for non-static built-in (native) types –default constructor and destructor.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Overview of C++ Polymorphism
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
1 Introduction to Object Oriented Programming Chapter 10.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
Pointers and Arrays Dynamic Variables and Arrays.
Pointers and References. Pointers & Memory 0x000x040x080x0B0x100x140x180x1B0x20.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Memory Management.
Object Lifetime and Pointers
Dynamic Storage Allocation
Overview 4 major memory segments Key differences from Java stack
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Motivation and Overview
C++ Memory Management Idioms
Dynamic Memory CSCE 121 J. Michael Moore.
Overview 4 major memory segments Key differences from Java stack
Overview of Memory Layout in C++
Dynamic Memory A whole heap of fun….
Dynamic Memory.
COP 3330 Object-oriented Programming in C++
Dynamic Memory CSCE 121.
Presentation transcript:

C++ Memory Overview 4 major memory segments Key differences from Java Global: variables outside stack, heap Code (a.k.a. text): the compiled program Heap: dynamically allocated variables Stack: parameters, automatic and temporary variables Key differences from Java Destructors of automatic variables called when stack frame where declared pops No garbage collection: program must explicitly free dynamic memory Heap and stack use varies dynamically Code and global use is fixed Code segment is “read-only” stack heap code global

Illustrating C++ Memory int g_default_value = 1; int main (int argc, char **argv) { Foo *f = new Foo; f->setValue(g_default_value); delete f; return 0; } void Foo::setValue(int v) { this->m_value = v; crt0 stack main Foo *f Foo: setValue Foo *this int v m_value heap code g_default_value global

Illustrating C++ Memory int g_default_value = 1; int main (int argc, char **argv) { Foo *f = new Foo; f->setValue(g_default_value); delete f; return 0; } void Foo::setValue(int v) { this->m_value = v; stack Foo *f Foo *this int v m_value heap code g_default_value global

Memory, Lifetimes, and Scopes Temporary variables Are scoped to an expression, e.g., a = b + 3 * c; Automatic (stack) variables Are scoped to the duration of the function in which they are declared Dynamically allocated variables Are scoped from explicit creation (new) to explicit destruction (delete) Global variables Are scoped to the entire lifetime of the program Includes static class and namespace members May still have initialization ordering issues Member variables Are scoped to the lifetime of the object within which they reside Depends on whether object is temporary, automatic, dynamic, or global Lifetime of a pointer/reference can differ from the lifetime of the location to which it points/refers

Direct Dynamic Allocation and De-allocation #include <iostream> using namespace std; int main (int, char *[]) { int * i = new int; // any of these can throw bad_alloc int * j = new int (3); int * k = new int[*j]; int * l = new int[*j]; for (int m = 0; m < *j; ++m) { l[m] = m; } delete i; delete j; delete [] k; delete [] l; return 0; Array vs. single instance new Fill in array values with loop Array vs. single instance delete

A Basic Issue: Multiple Aliasing int main (int argc, char **argv) { Foo f; Foo *p = &f; Foo &r = f; delete p; return 0; } Multiple aliases for same object f is a simple alias, the object itself p is a variable holding a pointer r is a variable holding a reference What happens when we call delete on p? Destroy a stack variable (may get a bus error there if we’re lucky) If not, we may crash in destructor of f at function exit Or worse, a local stack corruption that may lead to problems later Problem: object destroyed but another alias to it was then used Foo &r Foo f Foo *p

Memory Lifetime Errors Foo *bad() { Foo f; return &f; } Foo &alsoBad() { return f; Foo mediocre() { Foo * better() { Foo *f = new Foo; Automatic variables Are destroyed on function return But in bad, we return a pointer to a variable that no longer exists Reference from also_bad similar Like an un-initialized pointer What if we returned a copy? Ok, we avoid the bad pointer, and end up with an actual object But we do twice the work (why?) And, it’s a temporary variable (more on this next) We really want dynamic allocation here

More Memory Lifetime Errors int main() { Foo *f = &mediocre(); cout << good()->value() << endl; return 0; } Foo mediocre() { Foo f; return f; Foo * good() { return new Foo; Dynamically allocated variables Are not garbage collected But are lost if no one refers to them: called a “memory leak” Temporary variables Are destroyed at end of statement Similar to problems w/ automatics Can you spot 2 problems? One with a temporary variable One with dynamic allocation

More Memory Lifetime Errors int main() { Foo *f = &mediocre(); cout << good()->value() << endl; return 0; } Foo mediocre() { Foo f; return f; Foo *good() { return new Foo; Dynamically allocated variables Are not garbage collected But are lost if no one refers to them: called a “memory leak” Temporary variables Are destroyed at end of statement Similar to problems w/ automatics Can you spot 2 problems? One with a temporary variable One with dynamic allocation Key point Incorrect use is the real problem Need to examine and fully understand the details

Double Deletion Errors int main (int argc, char **argv) { Foo *f = new Foo; delete f; // ... do other stuff return 0; } crt0 stack main Foo *f f heap code g_default_value global

Double Deletion Errors int main (int argc, char **argv) { Foo *f = new Foo; delete f; // ... do other stuff return 0; } crt0 stack main Foo *f heap What could be at this location? Another heap variable Could corrupt heap code g_default_value global

A Safer Approach using Smart Pointers C++11 provides two key dynamic allocation features shared_ptr : a reference counted pointer template to alias and manage objects allocated in dynamic memory (we’ll mostly use the shared_ptr smart pointer in this course) make_shared : a function template that dynamically allocates and value initializes an object and then returns a shared pointer to it (hiding the object’s address, for safety) C++11 provides 2 other smart pointers as well unique_ptr : a more complex but potentially very efficient way to transfer ownership of dynamic memory safely (implements C++11 “move semantics”) weak_ptr : gives access to a resource that is guarded by a shared_ptr without increasing reference count (can be used to prevent memory leaks due to circular references)

Resource Acquisition Is Initialization (RAII)‏ Also referred to as the “Guard Idiom” However, the term “RAII” is more widely used for C++ Relies on the fact that in C++ a stack object’s destructor is called when stack frame pops Idea: we can use a stack object (usually a smart pointer) to hold the ownership of a heap object, or any other resource that requires explicit clean up Immediately initialize stack object with the allocated resource De-allocate resource in the stack object’s destructor

RAII Example: Guarding Newly Allocated Object RAII idiom example using shared_ptr #include <memory> using namespace std; shared_ptr<X> assumes and maintains ownership of aliased X Can access the aliased X through it (*spf) shared_ptr<X> destructor calls delete on address of owned X when it’s safe to do so (per reference counting idiom discussed next) Combines well with other memory idioms shared_ptr<Foo> createAndInit() { shared_ptr<Foo> p = make_shared<Foo> (); init(p);// may throw exception return p; } int run () { try { shared_ptr<Foo> spf = createAndInit(); cout << “*spf is ” << *spf; } catch (...) { return -1 return 0;

Reference Counting Basic Problem Solution Approach reference reference Resource sharing is often more efficient than copying But it’s hard to tell when all are done using a resource Must avoid early deletion Must avoid leaks (non-deletion) Solution Approach Share both the resource and a counter for references to it Each new reference increments the counter When a reference is done, it decrements the counter If count drops to zero, also deletes resource and counter “last one out shuts off the lights” reference reference Resource reference counter == 3

Reference Counting Example: Sharing an Object shared_ptr<Foo> createAndInit() { shared_ptr<Foo> p = make_shared<Foo> (); init(p);// may throw exception return p; } int run () { try { shared_ptr<Foo> spf = createAndInit(); shared_ptr<Foo> spf2 = spf; // object destroyed after // both spf and spf2 go away } catch (...) { return -1 return 0; Again starts with RAII idiom via shared_ptr spf initially has sole ownership of aliased X spf.unique() would return true spf.use_count would return 1 shared_ptr<X> copy constructor increases count, and its destructor decreases count shared_ptr<X> destructor calls delete on the pointer to the owned X when count drops to 0