CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Dynamic Memory Allocation

Similar documents
CSCI 104 Memory Allocation. Mark Redekopp David Kempe

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 6: Pointers

CS103 Unit 6 - Pointers. Mark Redekopp

CS103 Unit 6 - Pointers. Mark Redekopp

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

CS201- Introduction to Programming Current Quizzes

Exam 3 Chapters 7 & 9

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Abstract Data Types

Pointers, Dynamic Data, and Reference Types

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Pointers II. Class 31

Understanding Pointers

Homework #3 CS2255 Fall 2012

Pointers and Dynamic Memory Allocation

Variables, Memory and Pointers

Memory Management. CS449 Fall 2017

C/C++ Functions. Mark Redekopp

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

CSC 211 Intermediate Programming. Arrays & Pointers

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

FORM 2 (Please put your name and form # on the scantron!!!!)

C++ for Java Programmers

9.2 Pointer Variables. Pointer Variables CS Pointer Variables. Pointer Variables. 9.1 Getting the Address of a. Variable

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them.

C Pointers. ENGG1002 Computer Programming and Applica;ons Dr. Hayden Kwok Hay So Week 2. GeGng Hold of Memory. Sta;c: When we define a variable

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

Pointer Data Type and Pointer Variables

CS 101: Computer Programming and Utilization

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

Memory Allocation in C

Memory, Arrays, and Parameters

CS 161 Exam II Winter 2018 FORM 1


Run Time Environment

COMP 11 Class 17 Outline

CA31-1K DIS. Pointers. TA: You Lu

Introduction to Computer Science Midterm 3 Fall, Points

a data type is Types

Dynamic memory allocation (malloc)

Linked Memory. Pointers Linked Lists. September 21, 2017 Cinda Heeren / Geoffrey Tien 1

Dynamic memory allocation

LAB #8. GDB can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act:

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

Lecture 15a Persistent Memory & Shared Pointers

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Arrays. C Types. Derived. Function Array Pointer Structure Union Enumerated. EE 1910 Winter 2017/18

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

C:\Temp\Templates. Download This PDF From The Web Site

Computer Programming

CS103 Unit 5 - Arrays. Mark Redekopp

In Java we have the keyword null, which is the value of an uninitialized reference type

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

Memory and Pointers written by Cathy Saxton

LAB #8. Last Survey, I promise!!! Please fill out this really quick survey about paired programming and information about your declared major and CS.

CS 222: Pointers and Manual Memory Management

CS103 Unit 5 - Arrays. Mark Redekopp

primitive arrays v. vectors (1)

Pointers. Memory. void foo() { }//return

Linked Memory. Pointers Linked Lists. January 19, 2018 Cinda Heeren / Geoffrey Tien 1

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Algorithms & Data Structures

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

Week 3: Pointers (Part 2)

What is an algorithm?

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana

1.1. EE355 Unit 1. Course Overview & Review. Mark Redekopp

LSN 3 C Concepts for OS Programming

Principles of Programming Languages

COMP 2355 Introduction to Systems Programming

MM1_ doc Page E-1 of 12 Rüdiger Siol :21

Short Notes of CS201

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable

MEMORY ADDRESS _ REPRESENTATION OF BYTES AND ITS ADDRESSES

Dynamic Allocation of Memory

CS201 - Introduction to Programming Glossary By

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Arrays and Memory Management

! The address operator (&) returns the address of a. ! Pointer: a variable that stores the address of another

CS201 Some Important Definitions

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

CS102 Software Engineering Principles

Pointers and Terminal Control

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

Computer Programming

POINTER AND ARRAY SUNU WIBIRAMA

Dynamic Memory Allocation

Lecture 2, September 4

LOÏC CAPPANERA. 1. Memory management The variables involved in a C program can be stored either statically or dynamically.

Transcription:

CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 8: Dynamic Memory Allocation

Why use Pointers? Share access to common data (hold onto one copy, everybody points to it) Flexibility (dynamic data structures) Precisely control allocation/deallocation ourselves

Passing Arrays as Arguments In function declaration / prototype use type [] or type * When calling the function, simply provide the name of the array as the argument In /C++, array name by itself evaluates to the starting address of the array C+ does implicitly keep track of the size of the array Thus either need to have the function only accept arrays of a certain size Or need to pass the size (length) of the array as another argument void add_1_to_array_of_10(int []); void add_1_to_array(int *, int); int main() { int data[10] = {9,8,7,6,5,4,3,2,1,0; add_1_to_array_of_10(data); cout << data[0] = << data[0] << endl; add_1_to_array(data,10); cout << data[9] = << data[9] << endl; return 0; void add_1_to_array_of_10(int my_array[]) { int i=0; for(i=0; i < 10; i++){ my_array[i]++; void add_1_to_array(int *my_array, int size) { int i=0; for(i=0; i < size; i++){ my_array[i]++;

Command Line Arguments int main(int argc, char *argv[]) {... > encrypt tweet.txt encrypted.txt argc = 3 argv[0] = encrypt argv[1] = tweet.txt argv[2] = encrypted.txt

Pointers as Function Return Value Pointer value (i.e. the address) is still passed-by-value (i.e. a copy is made) The value of y is CHANGED by doit() and that change is visible when we return. Address 0x0000000 System Memory (RAM) 0xffffffff Code for all functions Data for doit Data for doit (x=0x20bd4, x = 0x20bd4 i) and return i = 2 link Data for main Data for main (a=??, y=3, ptr=0x20bd4) a=5, y[0]=2,y[1]=5 and return link ptr=0x20bd4 System stack area int main() { int a, y[2]= {3,5, *ptr; // assume y @ 0x20bd4 // assume ptr ptr = y; a = *doit(ptr); cout << a= << a << endl; cout << y[0]= <<y[0]<< endl; return 0; //! Remember * in a type/ // declaration Remember * in means a type! pointer // declaration // variable means pointer! int // variable! doit(int *x) { int* int doit(int i; *x) { *x = *x - 1; int i; i = *x; *x = *x - 1; x++; i = *x; return x++; i; return x; Output: a=5 y[0]=2

Why use Pointers? Share access to common data (hold onto one copy, everybody points to it) Flexibility (dynamic data structures) Precisely control allocation/deallocation ourselves

Dynamic Memory Alloca/on I want an array for student scores but I don t know how many students we have un/l the user tells me What size should I use to declare my array? int scores[??] Doing the following is not supported by all C++ compilers: int num; cin >> num; int scores[num]; // compilers require the array size // to be statically known All compilers support alloca/ng memory dynamically (i.e. at run- /me)

8 Dynamic Variables Dynamic variables: created during execu/on C++ creates dynamic variables using pointers new and delete operators: used to create and destroy dynamic variables new and delete are reserved words in C++ C++ Programming: Program Design Including Data Structures, Sixth Edition

Dynamic Memory & the Heap Code usually sits at low addresses Global variables somewhere amer code System stack (memory for each func/on instance that is alive) Local variables Return link (where to return) etc. Heap: Area of memory that can be allocated and de- allocated during program execu/on (i.e. dynamically at run- /me) based on the needs of the program Heap grows downward, stack grows upward In rare cases of large memory usage, they could collide and cause your program to fail or generate an excep/on/error 0 fffffffc Memory Code Globals Heap Stack (area for data local to a function)

10 Operator new intexp is any expression evalua/ng to a posi/ve integer new allocates memory (a variable) of the designated type and returns a pointer to it The allocated memory is unini/alized C++ Programming: Program Design Including Data Structures, Sixth Edition

11 Operator new Example: p = new int; Creates a variable during program execu/on somewhere in memory Stores the address of the allocated memory in p To access allocated memory, use *p A dynamic variable cannot be accessed directly Because it is unnamed

C++ new & delete operators new allocates memory from heap followed with the type of the variable you want or an array type declara/on double *dptr = new double; int *myarray = new int[100]; can obviously use a variable to indicate array size returns a pointer of the appropriate type if you ask for a new int, you get an int * in return if you ask for a new array (new int[10]), you get an int ** in return delete returns memory to the heap followed by the pointer to the data you want to de- allocate delete dptr; use delete [] for arrays delete [] myarray;

Dynamic Memory Alloca/on int main() { int *scores; int num; cout << How many students? << endl; cin >> num; scores = new int[num]; // can now access scores[0].. scores[num-1]; return 0; int main() { int *scores; int num; cout << How many students? << endl; cin >> num; scores = new int[num]; // can now access scores[0].. scores[num-1]; delete [] scores return 0; 0 Code Globals Heap 20bc0 00 20bc4 00 20bc8 00 20bcc 00 20bd0 00 fffffffc local vars Memory new allocates: scores[0] scores[1] scores[2] scores[3] scores[4]

14 Operator delete delete only marks the memory space as deallocated Pointer variable may s/ll contain address of deallocated memory space If you try to access via the pointer, could result in corrup/ng data or termina/on Avoid this by sezng pointers to NULL amer delete opera/on C++ Programming: Program Design Including Data Structures, Sixth Edition

15 Operator delete Memory leak: previously allocated memory that cannot be reallocated To avoid a memory leak, when a dynamic variable is no longer needed, destroy it to deallocate its memory delete operator: used to destroy dynamic variables Syntax: C++ Programming: Program Design Including Data Structures, Sixth Edition

16 Dynamic Arrays Dynamic array: array created during program execu/on Example: int *p; p = new int[10]; *p = 25; stores 25 into the first memory location p++; //to point to next array component *p = 35; stores 35 into the second memory location C++ Programming: Program Design Including Data Structures, Sixth Edition

17 Dynamic Arrays Can use array notation to access these memory locations Example: p[0] = 25; p[1] = 35; Stores 25 and 35 into the first and second array components, respectively An array name is a constant pointer C++ Programming: Program Design Including Data Structures, Sixth Edition

18 Dynamic Two- Dimensional Arrays You can create dynamic mul/dimensional arrays Examples: declares board to be an array of four pointers wherein each pointer is of type int creates the rows of board declares board to be a pointer to a pointer C++ Programming: Program Design Including Data Structures, Sixth Edition

19 Problem: Create a function to ask the user to input test scores 1. The function should ask the user for the number of test scores 2. Dynamically create an array of that size 3. Then ask the user to enter in each test score. 4. Return a pointer to the array of test scores