Overview 4 major memory segments Key differences from Java stack

Slides:



Advertisements
Similar presentations
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.
Advertisements

Informática II Prof. Dr. Gustavo Patiño MJ
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.
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
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.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
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.
February 11, 2005 More Pointers Dynamic Memory Allocation.
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.
C++ Memory Overview 4 major memory segments Key differences from Java
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.
Object-Oriented Programming in C++
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Chapter 7 Pointers: Java does not have pointers. Used for dynamic memory allocation.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
CSE 332: Memory management with C++ classes Memory Management with Classes Review: for non-static built-in (native) types –default constructor and destructor.
System Programming Practical Session 7 C++ Memory Handling.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
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.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
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.
Yan Shi CS/SE2630 Lecture Notes
Memory Management.
Object Lifetime and Pointers
Dynamic Storage Allocation
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
Memory Management with Classes
Overview 4 major memory segments Key differences from Java stack
Motivation and Overview
Pointers and Memory Overview
Pointers and Dynamic Variables
Advanced Programming Behnam Hatami Fall 2017.
Dynamically Allocated Memory
Dynamic Memory Allocation Reference Variables
CSC 253 Lecture 8.
CMSC 341 Prof. Michael Neary
CSC 253 Lecture 8.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Overview of Memory Layout in C++
Pointers, Dynamic Data, and Reference Types
Built-In (a.k.a. Native) Types in C++
Dynamic Memory A whole heap of fun….
Chapter 15 Pointers, Dynamic Data, and Reference Types
Given the code to the left:
Chapter 12 Pointers and Memory Management
Dynamic Memory A whole heap of fun….
Dynamic Memory A whole heap of fun….
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.
Pointers and dynamic objects
COP 3330 Object-oriented Programming in C++
Pointers and References
Pointers, Dynamic Data, and Reference Types
Pointers and references
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Overview 4 major memory segments Key differences from Java stack 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 (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 can differ from the lifetime of the location to which it points/refers

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: 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 Initialization Errors int main(int argc, char **argv) { Foo *f; cout << f->value() << endl; for (int i; i < argc; ++i) cout << argv [i] << endl; return 0; } Heap and stack memory is not initialized for us in C++ Get whatever was out in memory Unless we initialize it ourselves So we should always do so What happens when we dereference pointer f? If we’re lucky, a program crash If not, we get bad output Or worse, a local over-write, leading to problems later Is there anything else wrong with this code?

Memory Initialization Errors int main(int argc, char **argv) { Foo *f; cout << f->value() << endl; for (int i; i < argc; ++i) cout << argv [i] << endl; return 0; } Heap and stack memory is not initialized for us in C++ Get whatever was out in memory Unless we initialize it ourselves So we should always do so What happens when we dereference pointer f? If we’re lucky, a program crash If not, we get bad output Or worse, a local over-write, leading to problems later Is there anything else wrong with this code?

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 Foo mediocre() { Foo f; return f; } Foo * good() { return new Foo; int main() { Foo *f = &mediocre(); cout << good()->value() << endl; return 0; 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; ... return 0; } crt0 stack main Foo *f f heap code g_default_value global

Double Deletion stack heap What could be at this location? code global 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

Double Deletion stack heap code global int main (int argc, char **argv) { Foo *f = new Foo; delete f; //now call functions… } void baz(Foo * f) { return 0; crt0 stack main Foo *f baz heap code g_default_value global

Scopes of Variables vs. References Variables and the pointers and references to them may have different scopes May result in obvious kinds of lifetime errors we saw earlier But may also introduce more subtle issues of aliasing Still can risk destroying an object too soon or too late Card a_card; // stack object Destructor will be implicitly called when a_card is out of scope. Card* card_ptr = new Card; // heap object Requires explicit delete Don’t do these delete &a_card; // delete on a stack object a_card = *(new Card); // using new to get a temporary variable