1 Dynamic Memory Allocation Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series.

Slides:



Advertisements
Similar presentations
Informática II Prof. Dr. Gustavo Patiño MJ
Advertisements

Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
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.
1 Classes with Pointer Data Members (II) Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230.
Final Review Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series.
Wrap Up and Misc Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
1 Array, Pointer and Reference ( III ) Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures.
1 String Library and Stream I/O Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series.
Pointers and dynamic objects COMP171 Fall Pointers and dynamic objects/ Slide 2 Topics * Pointers n Memory addresses n Declaration n Dereferencing.
1 Array, Pointer and Reference ( IV ) Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures.
Main Index Contents 11 Main Index Contents Pointer Illustration Pointer Illustration Vertical / Horizontal View. Vertical / Horizontal View. Data Addresses.
Array, Pointer and Reference ( V ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
1 Midterm Review Ying Wu Electrical Engineering & Computer Science Northwestern University EECS230 Lectures Series.
1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series.
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.
Main Index Contents 11 Main Index Contents Pointer Illustration Pointer Illustration Vertical / Horizontal View. Vertical / Horizontal View. Data Addresses.
1 Array, Pointer and Reference ( I ) Ying Wu Electrical Engineering and Computer Science Northwestern University EECS 230 Lectures.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Linked List (I) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
CSC 107 – Programming For Science. Today’s Goal  Learn how arrays normally used in real programs  Why a function returning an array causes bugs  How.
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.
C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 Debugging: Catching Bugs ( II ) Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures.
Pointers OVERVIEW.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Array, Pointer and Reference ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
1 Writing a Good Program 8. Elementary Data Structure.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
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.
1 Chapter 15-2 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Object-Oriented Programming in C++
Dynamic memory allocation and Pointers Lecture 4.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
1 C++ Classes (I) Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series.
Function ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
1 CSE 2341 Object Oriented Programming with C++ Note Set #2.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 24: Pointers and Dynamic Allocation.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Memory management operators Dynamic memory Project 2 questions.
Variables and memory addresses
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
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.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 24: Pointers and Dynamic Allocation.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
APS105 Malloc and 2D Arrays (text Ch6.4, Ch10.2).
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Dynamic Memory A whole heap of fun….
Chapter 15 Pointers, Dynamic Data, and Reference Types
Dynamic Memory A whole heap of fun….
CS150 Introduction to Computer Science 1
Dynamic Memory A whole heap of fun….
CS250 Introduction to Computer Science II
CS150 Introduction to Computer Science 1
Pointers and dynamic objects
Presentation transcript:

1 Dynamic Memory Allocation Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series

2 What to learn today? What motivate us to manage the memory dynamically? How to allocate memory dynamically?

3 Will it work? int main( ) { int size; cin >> size; int arr[size] for(int i=0;i<size;i++) arr[i] = i; return 0; } I know what you want to do. But this method won’t work. So, how can we do that? Keep it and we will see in this lectures!

4 Variable Name Database Task: to create a name database, in which each entry is a name of a variable, e.g., “var_1”, “a”, … If we have such a DB, we can search an entry given a name.

5 Arrays of Pointers Arrays can contain pointers –Commonly used to store an array of strings char *suit[ 4 ] = {"Hearts", "Diamonds", "Clubs", "Spades" }; –Each element of suit is a pointer to a char * (a string) –The strings are not in the array, only pointers to the strings are in the array –suit array has a fixed size, but strings can be of any size suit[3] suit[2] suit[1] suit[0]’H’’e’’a’’r’’t’’s’ ’\0’ ’D’’i’’a’’m’’o’’n’’d’’s’ ’\0’ ’C’’l’’u’’b’’s’ ’\0’ ’S’’p’’a’’d’’e’’s’ ’\0’

6 Name DB using Array of Ptrs bool Search(const char*, int&); char *g_nameDB[4]; void main() { g_nameDB[0] = “a”; g_nameDB[1] = “var_1”; g_nameDB[2] = “xyz”; g_nameDB[4] = “temp”; char query[100]; cin.getline(query,100); int ind; if(Search(query, ind)){ cout << “Found “ << g_nameDB[ind]); else cout << “was not found!” << endl; } bool Search(const char* q, int& index) { bool isFound = false; for(int k=0;k<4;k++){ if( !strcmp(g_nameDB[k], q)){ index = k; isFound = true; break; } return isFound; }

7 Question? In the previous example, the DB is fixed in the main function. However, we want to get it done in a more flexible way: –Allowing us to add an entry –Allowing us to delete a entry

8 Motivation for DMA When we declare an array, we have to specify the size; otherwise the compiler will never know how much memory it should allocate to this array. Therefore, we have to use e.g., int arr[100] It makes the code less flexible However, if we have no idea about the size of the array in advance, what can we do? Solution I: use a larger size, say Solution II: my code can perform part of the memory management

9 The Idea We need some mechanisms that: –let my program decide memory usage –ask the O/S to allocate as much as memory as I want –O/S tells me where and how much the memory are –free the memory to O/S when I don’t need them

10 Implementation in C++ Dynamic Memory Allocation –new Creates an object of the proper size calls its constructor returns a pointer of the correct type –delete Destroys object frees space

11 Example: Allocate an object New int *ptr; ptr = new int; (*ptr) = 5; new creates an integer, returns pointer delete delete ptr; free the memory ptr

12 Allocate A Set of Object New a set double *ptr; int size = 10; ptr = new double [size]; new creates an double array, returns pointer to the array delete a set delete [] ptr; free the memory int num = 100; double *arr = new double [num]; … delete [] arr; num = 10; arr = new double [num]; … delete [] arr; Use your debugger to check what happens!!

13 // global variables to define the varDB #define MAX_SIZE_DB 100; char*gVarDB_Name[MAX_SIZE_DB]; // MAX_SIZE_DB is the maximum intgVarDB_Size; // the size of the DB doublegVarDB_Value[MAX_SIZE_DB]; // functions related to the varDB // Initialize the system variable DB void VarDB_Init() { // the first one is reserved for "ans" gVarDB_Size = 1; for(int i=0; i<MAX_SIZE_DB; i++){ gVarDB_Value[i] = 0.0; gVarDB_Name[i] = NULL; } VarDB_SetVarName(0,"ans"); } A sol. to the varDB

14 // set a name entry to the variable DB bool VarDB_SetVarName(const int& index, const char* name) { assert(index < gVarDB_Size); boolcode = true; if(gVarDB_Name[index]!=NULL){ if(strlen(gVarDB_Name[index])!=0) { delete [] gVarDB_Name[index]; } gVarDB_Name[index] = new char [strlen(name) + 1]; if(gVarDB_Name[index]){ strcpy(gVarDB_Name[index], name); } elsecode = false; return code; }

15 ATTENTON DMA is quite flexible and powerful But if not used carefully and correctly, it will be a disaster to your code –Memory leak! –A lesson The way to prevent turmoil –Pair new and delete –Know exactly new [] and delete [] –Know exactly what you want to do!

16 Questions for today 1.what is wrong and how to correct? char *string; string = new char [30]; free(string); 2.what is wrong and how to correct? double *pt; pt = new double [30]; delete double; 3.what is wrong and how to correct? int* myfunc(){ int arr[10]; for(int i=0;i<10;i++) arr[i] = 0; return arr; }

17 Question to think about Constructing a 2D array. A 2D array can be seen by a 2D pointer Will the following code work (to create a 3x4 matrix)? int **mat; for(int i=0;i<3;i++) mat[i] = new int [4]; How to delete this 2D array?