Overview of Memory Layout in C++

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
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++ copy control I Copy Control (Part I) Copy control consists of 5 distinct operations –A copy constructor initializes an object by duplicating.
Chapter 15 Memory Management: Four main memory areas for a C++ program: Code: code for instructions, methods, etc. static data: Global variables (declared.
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
. Plab – Tirgul 10 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
Run-Time Storage Organization
Run time vs. Compile time
Plab – Tirgul 8 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
Memory organization and usage A computer’s memory is, at its lowest level, composed of binary digits (bits). The memory is organized into bytes, which.
OOP Languages: Java vs C++
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
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.
1 Data Structures - CSCI 102 CS102 C++ Pointers & Dynamic Objects Prof Tejada.
C++ Memory Overview 4 major memory segments Key differences from Java
 Managing the heap  Resource acquisition is initialization (RAII)  Overriding operator new and delete  Class-based memory pools.
Object-Oriented Programming in C++
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.
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.
CSI 3125, Preliminaries, page 1 Class. CSI 3125, Preliminaries, page 2 Class The most important thing to understand about a class is that it defines a.
1 Introduction to Object Oriented Programming Chapter 10.
PROGRAMMING 1 – HELPER INSTRUCTIONS ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY 1.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
Memory Management in Java Mr. Gerb Computer Science 4.
Code Generation Instruction Selection Higher level instruction -> Low level instruction Register Allocation Which register to assign to hold which items?
Design issues for Object-Oriented Languages
Memory Management.
Jim Fawcett CSE 691 – Software Modeling and Analysis Fall 2000
Constructors and Destructors
Eine By: Avinash Reddy 09/29/2016.
Object Lifetime and Pointers
C ++ MULTIPLE CHOICE QUESTION
Exceptions David Rabinowitz.
Names and Attributes Names are a key programming language feature
Overview 4 major memory segments Key differences from Java stack
Copy Constructor / Destructors Stacks and Queues
CSE 374 Programming Concepts & Tools
Motivation and Overview
C++ Memory Management Idioms
Dynamic Memory CSCE 121 J. Michael Moore.
This pointer, Dynamic memory allocation, Constructors and Destructor
Advanced Programming Behnam Hatami Fall 2017.
CSC 253 Lecture 8.
Array Lists Chapter 6 Section 6.1 to 6.3
CSC 253 Lecture 8.
Overview 4 major memory segments Key differences from Java stack
understanding memory usage by a c++ program
Memory Allocation CS 217.
Chapter 12 Pointers and Memory Management
Constructors and Destructors
Destructor CSCE 121 J. Michael Moore.
Arrays an array of 5 ints is filled with 3,2,4,1,7
Destructor CSCE 121.
Overview of C++ Polymorphism
Dynamic Memory A whole heap of fun….
Dynamic Memory.
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
Pointers and References
Dynamic Memory CSCE 121.
Destructors, Copy Constructors & Copy Assignment Operators
Exceptions.
Destructors, Copy Constructors & Copy Assignment Operators
CS 144 Advanced C++ Programming April 30 Class Meeting
Object and its encapsulation
CSE 333 – Section 5 C++ (1m).
SPL – PS2 C++ Memory Handling.
CSE 303 Concepts and Tools for Software Development
Presentation transcript:

Overview of Memory Layout in C++ 4 major memory segments 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

Dynamic Allocation and Deallocation #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[3]; 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

Exercise Copy and paste (or type) this code into Visual Studio (or emacs on grid) Add an appropriate try-catch block around the statements that can throw an exception Before you can build, what other statements must also go into the try-catch block? Why? Print all the elements of each dynamic allocation before it’s destroyed #include <iostream> using namespace std; int main (int, char *[]) { int * i = new int; int * j = new int (3); int * k = new int[3]; 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;

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 (see Singleton Pattern) 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 is independent of the lifetime of the location to which it points/refers (e.g., new and delete)

Resource Acquisition is Initialization (RAiI) “Guard idiom” expands on constructor/destructor idiom C++ has an auto_ptr class template (a “generic” programming construct) auto_ptr<X> assumes ownership of a pointer-to-X auto_ptr<X> destructor calls delete on the pointer if the auto_ptr still owns it Call release to break ownership by an auto_ptr<X> (once it’s safe to do so) Foo *createAndInit() { Foo *f = new Foo; auto_ptr<Foo> p(f); init(f); // may throw exception p.release(); return f; } int run () { try { Foo *d = createAndInit(); return 0; } catch (...) { return 1;

More About auto_ptr and RAiI auto_ptr<X> copy constructor transfers ownership from the older to the newer one E.g., if you pass an auto_ptr by value to a function E.g., if you create a vector of auto_ptr variables E.g., if you return an auto_ptr by value as a function result Ownership is passed along a chain of responsibility for the memory Makes sure it’s cleaned up once at end of chain auto_ptr<Foo> createAndInit() { auto_ptr<Foo> p(new Foo); p = init(p); // may throw exception return p; } int run () { try { auto_ptr<Foo> q(createAndInit()); // do something with object return 0; } catch (...) { return 1;

Exercise Download, compile and run the array_exercise5.cc and array_exercise5.h files Provided on the CSE 232 course web page While we do that we’ll talk about what the program does What does the output tell you about What memory management it’s doing correctly? What memory management it’s doing incorrectly? Please try fixing the things it’s doing incorrectly E.g., making sure all dynamically allocated memory is cleaned up E.g., making sure object constructors get a matching destructor call Please try improving at least one thing that it could be doing better (assuming we still want all the dynamic allocations) E.g., using auto_ptr everywhere it makes sense to use it (but not where it doesn’t make sense to do so)