Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.

Slides:



Advertisements
Similar presentations
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Advertisements

Informática II Prof. Dr. Gustavo Patiño MJ
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.
CS 330 Programming Languages 10 / 16 / 2008 Instructor: Michael Eckmann.
CSE 2501 Review Declaring a variable allocates space for the type of datum it is to store int x; // allocates space for an int int *px; // allocates space.
Dynamically Allocated Arrays May 2, Quiz 5 Today.
Pointers. 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.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
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.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Pointer Data Type and Pointer Variables
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Presented by: Mojtaba Khezrian. Agenda Object Creation Object Storage More on Arrays Parameter Passing For Each VarArgs Spring 2014Sharif University of.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
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.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
1 Records Record aggregate of data elements –Possibly heterogeneous –Elements/slots are identified by names –Elements in same fixed order in all records.
Peyman Dodangeh Sharif University of Technology Fall 2013.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. C H A P T E R F I V E Memory Management.
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.
SPL – Practical Session 2 Topics: – C++ Memory Management – Pointers.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Pointers You are not responsible for virtual functions (starting on.
1 Chapter 15-2 Pointers, Dynamic Data, and Reference Types Dale/Weems.
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.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Object-Oriented Programming in C++
Dynamic memory allocation and Pointers Lecture 4.
Pointers in C++. 7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Chapter 7 Pointers: Java does not have pointers. Used for dynamic memory allocation.
Review 1 List Data Structure List operations List Implementation Array Linked List.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Today: –Two simple binding examples. –Function Hiding.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
POINTERS AND MEMORY ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY 1.
Objects and Memory Mehdi Einali Advanced Programming in Java 1.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
Cinda Heeren / Geoffrey Tien
Pointers Revisited What is variable address, name, value?
Dynamically Allocated Memory
Dynamic Memory Allocation
CSC 253 Lecture 8.
CSC 253 Lecture 8.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers And Memory Acknowledgement: THE Slides are Prepared FROM SLIDES PROVIDED By NANCY M. AMATO AND Jory Denny.
Dynamic Memory.
Pointers, Dynamic Data, and Reference Types
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Memory and C++ Pointers

 C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January 2010Greg Mori2

// Java code // in function, f … int arr[]; arr = getOrdArray(5); // … …arr f …null … n getOrdArray 5 stack (static) public int[] getOrdArray(int n){ int arr[] = new int[n]; for (int i = 0; i < arr.length; ++i){ arr[i] = i * 2 + 1; } return arr; } heap (dynamic) arr January 20103Greg Mori

// in function, f … // C++ code int *arr; arr = getOrdArray(5); // … …arr f …null … n getOrdArray 5 stack int * getOrdArray(int n){ int *arr = new int[n]; for (int i = 0; i < n; ++i){ arr[i] = i * 2 + 1; } return arr; } heap arr

January 2010Greg Mori5

 In C++:  Both primitive types and objects can be allocated either on the stack or on the heap  Both primitive type and object value and reference variables are allowed ▪Hence, there needs to be C++ notation to distinguish between the two January 2010Greg Mori6

 There are two ways to refer to things in C++  The first is pointers  The * character is used to denote a pointer January 2010Greg Mori7 // n is a Node object Node n; // n is a pointer to a Node object Node *n; // i is an integer variable int i; // i is pointer to an integer variable int *i;

 Variables in methods are allocated in stack memory  C++ uses the keyword new to allocate space in the heap Greg Mori8 // n is a Node object, in stack Node n; // np is a pointer to a Node variable, np is in stack Node *np; // new creates a Node object, in heap // np points to this object np = new Node(); January 2010

nnp f null … stack heap Node object // n is a Node object, in stack Node n; // np is a pointer to a Node variable, np is in stack Node *np; // new creates a Node object, in heap // np points to this object np = new Node(); January 20109Greg Mori

 In C++, you can do the same with primitive types, e.g.: int Greg Mori10 // i is an integer variable, in stack int i; // ip is pointer to an integer variable, in stack int *ip; // new creates an integer variable, in heap ip = new int; January 2010

iip f null … stack heap ? // i is an integer variable, in stack int i; // ip is pointer to an integer variable, in stack int *ip; // new creates an integer variable, in heap ip = new int; January Greg Mori

 How do we access the contents of the thing a pointer points to?  This is called “dereferencing” a pointer ▪The * notation is used again January 2010Greg Mori12 // ip is pointer to an integer variable, in stack int *ip; // new creates an integer variable, in heap ip = new int; // *ip is the contents of the new integer *ip = 5; int i = *ip;

iip f null … stack heap ? // ip is pointer to an integer variable, in stack int *ip; // new creates an integer variable, in heap ip = new int; // *ip is the contents of the new integer *ip = 5; int i = *ip; 5 5 January Greg Mori

 There is a shorthand for following pointers and accessing object methods / variables  Uses the -> characters January 2010Greg Mori14 // np is a pointer to a Node variable, np is in stack // new creates a Node object, in heap // np points to this object Node *np = new Node(5); // both of these run the getData method on the Node object int i = (*np).getData(); int i = np -> getData();

 C++ allows one to obtain the address of an existing object / variable  This is called “referencing” ▪Uses the & operator (“address of”) January 2010Greg Mori15 // i is an integer variable, in stack int i; // ip is pointer to an integer variable, in stack int *ip; // ip refers to the memory where i resides ip = &i;

iip f null … stack heap 5 // i is an integer variable, in stack int i; // ip is pointer to an integer variable, in stack int *ip; // ip refers to the memory where i resides ip = &i; *ip = 5; January Greg Mori

January 2010Greg Mori17

 Java does Garbage Collection for you  C++ you need to do it yourself  If you don’t want an object any longer, call delete ▪If it’s an array, call delete [ ], which calls delete on all array elements  Bugs result if mistakes are made January 2010Greg Mori18

np f null … stack heap // np is a pointer to a Node variable, np is in stack // new creates a Node object, in heap, np points to this object Node *np = new Node(); // delete frees the heap memory referred to by np delete np; Node object January Greg Mori

 In C++ objects can be in stack memory (unlike Java)  Delete is automatically called on them when a method returns  Don’t manually delete them January 2010Greg Mori20

// in function, f … Node n; g(); // … … n f … null … stack (static) void g (){ Node m; Node r; } heap (dynamic) nodeObj m g r … … delete is called on m and r January Greg Mori

 Two major bug types can result if mistakes are made  Memory leaks  Dangling pointers January 2010Greg Mori22

 Memory leaks occur if there is heap memory which is not pointed to by any variable (at any scope)  No pointers to the memory in the current method nor any below it on the stack ▪Including global variables  There is no way to access the memory  The system will not use the memory for another object/variable  Eventually, you might run out of memory January 2010Greg Mori23

// in function, f … g(); // … … f … … stack (static) void g (){ Node *m = new Node(); } heap (dynamic) m g … … This memory is not accessible Node object January Greg Mori

// in function, f … Node *n; n = g(); // … … f … … stack (static) Node * g (){ Node *m = new Node(); return m; } heap (dynamic) m g … … Node object n January Greg Mori

 Once you call delete, or a method returns, memory is gone  If you try to refer to this memory you will get an error*  If it is being used by something else ▪Which will likely happen, but the error symptoms can be confusing January 2010Greg Mori26

// in function, f … int *ip = new int; int *jp = ip; *ip = 5 delete ip; // … *jp = 6; … f … … stack (static) heap (dynamic) This memory is not available 5 ipjp January Greg Mori

// in function, f … Node *n; n = g(); // … … f … … stack (static) Node * g (){ Node m; return &m; } heap (dynamic) m g nodeObj … … n This memory is not available January Greg Mori

January 2010Greg Mori29

 There are two ways to do refer to things in C++:  Pointers ▪Which we just did  References January 2010Greg Mori30

 C++ also has references in addition to pointers  References can be thought of as a restricted form of pointer  A few differences, key ones: ▪References cannot be NULL, pointers can ▪References cannot be reassigned, pointers can ▪This means they must be assigned at declaration time ▪Different syntax for access ▪Leads to cleaner code (but perhaps harder to understand) January 2010Greg Mori31

 The & character is used to denote references ▪Yes, the same character as address-of January 2010Greg Mori32 // n is a Node object, in stack Node n; // nr is a reference to a Node object, in stack // nr refers to the object n Node &nr = n;

nnr f null … stack heap Node object // n is a Node object, in stack Node n; // nr is a reference to a Node object, in stack // nr refers to the object n Node &nr = n; January Greg Mori

 References are used with same syntax as Java  Use the. character January 2010Greg Mori34 // n is a Node object, in stack Node n; // nr is a reference to a Node object, in stack // nr refers to the object n Node &nr = n; // both of these call the getData() method on the Node int i = n.getData(); int i = nr.getData();

 Often used for function / method parameters  “Pass by reference” vs. “Pass by value” 35 void foo (int x) { x=2; } int main () { int y = 4; foo(y); cout << y; return 0; } void foo (int& x) { x=2; } int main () { int y = 4; foo(y); cout << y; return 0; }

January 2010Greg Mori36

 Where do variables go?  C++ ▪If it’s a variable declaration, in stack ▪If it’s a new statement, in heap ▪In C++, both primitive types and objects can go in either stack or heap January 2010Greg Mori37

 How do I refer to variables?  C++ ▪Pointers ▪* notation  * in type to denote "it's a pointer to a"  * in usage to denote "follow this pointer to" ▪References ▪& notation January 2010Greg Mori38

 How do I manage memory?  C++ ▪Call delete manually (or delete [ ] for arrays) ▪Watch out for bugs  Memory leaks (forgot to delete)  Dangling pointers/references (deleted when you shouldn't have) January 2010Greg Mori39

 Carrano  Ch. 4.1 January 2010Greg Mori40