Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.

Slides:



Advertisements
Similar presentations
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Advertisements

Chapter 6 Data Types
Chapter 17 vector and Free Store John Keyser’s Modifications of Slides By Bjarne Stroustrup
Dynamic Allocation Eric Roberts CS 106B February 4, 2013.
Introduction of Memory Allocation. Memory Allocation There are two types of memory allocations possible in c. Compile-time or Static allocation Run-time.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
Informática II Prof. Dr. Gustavo Patiño MJ
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.
Run-Time Storage Organization
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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
Operator Overloading and Memory Management. Objectives At the conclusion of this lesson, students should be able to: Overload C++ operators Explain why.
Pointer Data Type and Pointer Variables
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
CS352-Week 2. Topics Heap allocation References Pointers.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
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.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays 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.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 15: More-Advanced Concepts.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
Pointers OVERVIEW.
1 Writing a Good Program 8. Elementary Data Structure.
C++ Memory Overview 4 major memory segments Key differences from Java
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.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Object-Oriented Programming in C++
Concordia TAV 2002 Comp5421_421 Comp5421 Object Oriented Programming Using C++ Efficiently Lecture 4 (2) Tianxiang Shen Summer 2002 Department of Computer.
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.
C++ REVIEW – POINTERS AND TEST DRIVEN DEVELOPMENT.
C++ Pointers Read Chapter 2 (P ). COP3530 – C++ Pointers Pointers Pointers provide a method of referencing the memory location of variables provide.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
UFS003C3 Lecture 15 Data type in C & C++ Using the STL.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
Memory Management in Java Computer Science 3 Gerb Objective: Understand references to composite types in Java.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
COMPUTER PROGRAMMING. Array C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
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.
Data Structures in C++ Pointers & Dynamic Arrays Shinta P.
Container Classes. How do we do better? Tough to delete correctly: startLocation.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Memory Management.
Overview 4 major memory segments Key differences from Java stack
Pointers Revisited What is variable address, name, value?
Dynamic Memory CSCE 121 J. Michael Moore.
Pointers and Dynamic Variables
Dynamically Allocated Memory
Dynamic Memory Allocation
Overview 4 major memory segments Key differences from Java stack
understanding memory usage by a c++ program
Pointers and Dynamic Variables
Dynamic Memory A whole heap of fun….
Dynamic Memory A whole heap of fun….
Dynamic Memory A whole heap of fun….
Dynamic Memory.
Dynamic Memory CSCE 121.
Run-time environments
Presentation transcript:

Pointers and Dynamic Variables

Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new operator * Save an address in a pointer * Understand where dynamically allocated data is stored Know how and when to delete dynamically allocated data Understand how a Vector works.

Dynamic Memory Allocation Review: Consider the following code: int valueOne = 10; int someFunction( ) { int valueTwo = 5;... } int main ( ) {... this is a global variable it is stored in the data segment. this is a local variable it is stored on the stack.

Dynamic Memory Allocation Review: Consider the following code: int valueOne = 10; int someFunction( ) { int valueTwo = 5;... } int main ( ) {... valueOne exists for the entire life of the program. valueTwo comes into existence when it is declared, and disappears when the function ends.

What if you want to control when a variable comes into existence, and when it goes away?

int* a = new int; CoinBank* myBank = new CoinBank(5,3); This is a pointer. This variable is stored on the heap. Storage from the heap is allocated dynamically as your program executes, These variables come into existence when they are declared. They don’t have names, but are accessed through pointers. They exist and take up memory until explicitly deleted. The new operator

Some languages, like Java and C# have a garbage collector to clean up data on the heap that is no longer in use. C++ does not – you have to do it!

delete Dynamically allocated variables will stay around until you explicitly delete them. Thus, they are completely under programmer control. To delete a dynamically allocated variable you would write delete a; where a is a pointer to the variable. When dynamically allocated variables are not properly deleted, your program will have a “memory leak”, which is really bad.

Dynamic Arrays Recall that when we talked about arrays, we noted that the array size given in the array declaration had to be a constant value. That is, the array size had to be fixed at compile time. This presents some difficulties: * either we guess too low and the array is not big enough to hold all of the data required, or * we guess to high and we waste space because elements of the array are not used.

One approach to solving this problem is to allocate the storage required for the array at run-time. int size; cout << “How big is the array?”; cin >> size; int *myArray; myArray = new int [size]; since we are allocating storage at run-time, we are allowed to use a variable as the array size.

Now, remembering the relationship between an array name and a pointer, we can use the dynamic array just like a normal array… myArray [5] = 15; cout << myArray[n]; Remember, myArray is just the name of the pointer where we saved the address returned by the new operator.

delete [ ] Whenever you use [ ] with new to allocate an array dynamically, you must use the corresponding form of the delete, delete [ ]. That is, if you write int *myArray; myArray = new int [10]; You must write delete [ ] myArray; to delete the array!

If you do not delete dynamically allocated data when you are done with it, your program may crash and it has the potential to crash your computer.

The -> Operator When we dynamically allocate storage for an object, we no longer use the dot operator to access its data members. Instead we use the -> operator. piggyBankPtr = new PiggyBank; piggyBankPtr->moneyInBank = 12.45;

Vectors

Internally, a Vector is just an array that has been dynamically allocated. Recall that a Vector has the following functions (among others): * constructors * size( ) returns the number of elements in the vector * capacity( ) returns the maximum number of elements that the vector can hold. * push_back(elem) adds elem to the end of the vector * clear( ) removes all of the elements from the vector * at(idx) returns the element at index idx * [idx] returns the element at index idx

Vector object pointer to array size capacity dynamic array

When a Vector is full, and you push another element into the vector, it automatically doubles its capacity. It does this by dynamically allocating another array that is twice as big as the existing one. Then it copies the data from the existing array into the new one. After of the data is copied, it deletes the old array.