Pointers & Dynamic Memory

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

Introduction to Linked Lists In your previous programming course, you saw how data is organized and processed sequentially using an array. You probably.
R4 Dynamically loading processes. Overview R4 is closely related to R3, much of what you have written for R3 applies to R4 In R3, we executed procedures.
Dynamic Memory Allocation (also see pointers lectures) -L. Grewe.
Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
C Programming - Lecture 5
Informática II Prof. Dr. Gustavo Patiño MJ
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
Pointers and dynamic objects COMP171 Fall Pointers and dynamic objects/ Slide 2 Topics * Pointers n Memory addresses n Declaration n Dereferencing.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Buffer Overflow Attacks. Memory plays a key part in many computer system functions. It’s a critical component to many internal operations. From mother.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
Variables and Objects, pointers and addresses: Chapter 3, Slide 1 variables and data objects are data containers with names the value of the variable is.
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.
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.
C Programming in Linux Jacob Chan. C/C++ and Java  Portable  Code written in one system and works in another  But in C, there are some libraries that.
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 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
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.
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.
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation Suppose we defined the data type: struct custrec.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
ECE Application Programming
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
1 2 2 Call The Project Dynamic-Memory 4 4 # include "Utilities.hpp" int main(int argc, char * argv[]) { short int *PtrNo; (*PtrNo) = 5; printf ("(*PtrNo)
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Dale Roberts, Lecturer Data Structure.
CSE 220 – C Programming malloc, calloc, realloc.
Dynamic Storage Allocation
Memory allocation & parameter passing
Functions & Memory Maps Review C Programming Language
C Primer.
Introduction to Linked Lists
Review C Programming Language
OOP-4-Templates, ListType
Checking Memory Management
CSCI206 - Computer Organization & Programming
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Dynamic Memory Allocation
This pointer, Dynamic memory allocation, Constructors and Destructor
Circular Buffers, Linked Lists
Announcements Homework #7 due Monday at 3:00pm
Pointers, Dynamic Data, and Reference Types
Dynamic Memory Allocation
Memory Allocation CS 217.
Welcome to Intro to C/C++ CISC 192
EECE.2160 ECE Application Programming
Beginning C for Engineers
Dynamic Memory A whole heap of fun….
Jeff West - Quiz Section 8
EECE.2160 ECE Application Programming
Dynamic Memory A whole heap of fun….
Homework Continue with K&R Chapter 5 Skipping sections for now
Data Structures & Algorithms
C Programming - Lecture 5
CSE 153 Design of Operating Systems Winter 2019
Welcome to Intro to C/C++ CISC 192
15213 C Primer 17 September 2002.
Pointers, Dynamic Data, and Reference Types
CSE 303 Concepts and Tools for Software Development
Presentation transcript:

Pointers & Dynamic Memory Review C Pointers Introduce C++ Pointers Data Abstractions CSCI-2320 Dr. Tom Hicks Computer Science Department

Write Down Important Link! c Write Down Important Link! http://carme.cs.trinity.edu/ thicks/2320/Schedule.html http://carme.cs.trinity.edu/thicks/2320/Schedule.html 2

c Objectives For Today 3

What You Should Do For Next Class Review C Dynamic Memory  malloc & free Do C++ Dynamic Memory  new & delete Begin C++ Classes

Assignment For Next Tuesday c Assignment For Next Tuesday 5

What You Should Do For Next Class Read Course Outline Complete the two-page questionnaire. Install Visual Studio 2017 Professional On Your Computer (if you have not done so) Complete OOP-1 Homework. (It is the longest lab form that you will do all semester - but only two pages of it have not been in the review recommendations that I sent out to those registered during the break) It Is Important That We Make Sure That The Review Material Does Not Prevent You From Completing The CSCI 2320 Material.

Check Web Site For Quizzes Practice - Review For Upcoming Quiz 1 Using Visual Studio Check The Class Schedule Daily! I Will Either Announce Quizzes In Class Or Post On The Web Site Two Days In Advance

The Search Capability Is Important! Recommendation If You Are Viewing My Slides Sets To Learn The Material  View The PPS The Annimation Important! If You Are Answering The Short Answer Questions On The Homework Labs  View PDF The Search Capability Is Important! 8

Make A Copy Of Project Review C Pointers! 9

Call The Project Dynamic-Memory 3

Review Pointers 11

printf("PtrNo = %ld\n", PtrNo); Add This Code To Main # include "Utilities.hpp" int main(int argc, char * argv[]) { puts ("-------------- Start Of Main --------------\n"); short int *PtrNo; printf("PtrNo = %ld\n", PtrNo); puts("--------------- End Of Main ---------------\n"); HitCarriageReturnToContinue(); return (0); } Run The Program

Most C/C++ Compilers Will Generate No Errors Visual Studio Provides A Number Of Safeguards That Is Not Incorporated Into Other Compilers  Memory  gets_s, strcpy_s, etc.

Memory Maps Often Help Us To See What Is Happening What Is The Problem? short int *PtrNo; Unknown Value In &1000? *PtrNo &1000 4 bytes  * short int ?? Memory Maps Often Help Us To See What Is Happening

Acceptable Range Of Values For PtrNo 15 15

Valid Memory Address? short int *PtrNo; ?? 1 GB = 1,048,576 bytes &1000 4 bytes  * short int 8,387,743 1 GB = 1,048,576 bytes If Your Computer Has 8 GB of RAM, Valid Memory Addresses Would Be 8,387,743 <= ?? <= 0 On most C/C++ compilers, if the ?? Garbage memory address is in the Valid Range, the compiler continues: (*PtrNo) = 5  Would Change Something  It may mess up your word processor  it may mess up your ability to access the Internet  it may mess up your ability to print  it may mess up another part of the program,  etc.

InValid Memory Address? short int *PtrNo; ?? *PtrNo &1000 4 bytes  * short int 1 GB = 1,048,576 bytes If Your Computer Has 8 GB of RAM, Valid Memory Addresses Would Be 8,387,743 <= ?? <= 0 8,387,743 On most C/C++ compiler(*PtrNo) = 5  Would Crash The System. This means that a program might compile one moment (because ?? is in the valid memory range) and not compile the next moment.

Set Ptrs To NULL 18 18

Better Practice  Avoid Dangling Pointers # include "Utilities.hpp" int main(int argc, char * argv[]) { puts ("-------------- Start Of Main --------------\n"); short int *PtrNo = NULL; printf("PtrNo = %ld\n", PtrNo); puts("--------------- End Of Main ---------------\n"); HitCarriageReturnToContinue(); return (0); } PtrNo &1000 4 bytes  * short int NULL Hopefully You Learned This In Your C Class

Review Dynamic Memory Pointers 20 20

Review Malloc & Free (from C) - 1 2 bytes  short int ?? 924240 &924240 short int *PtrNo = NULL; 4 bytes  * short int PtrNo NULL &1000 PtrNo = (short int *) malloc(sizeof(short int)); free(PtrNo); This malloc call requests, of the compiler, a contiguous block of memory that is 2 bytes in size. If the compiler is unable to provide this, then PtrNo is filled with NULL. Function free must return the allocated memory back to the operating system; failure to do that results in a "memory leak".

Review Malloc & Free (from C) - 2 short int *PtrNo = NULL; 4 bytes  * short int NULL If the compiler is unable to provide this, then PtrNo is filled with NULL  ASSUME THAT IS THE CASE! PtrNo &1000 PtrNo = (short int *) malloc(1000000* sizeof(short int)); free(PtrNo); This malloc call requests, of the compiler, a contiguous block of memory that is 2,000,000 bytes in size. Function free will create a problem when it tries to return 2,000,000 bytes of memory beginning at &0!

Review Malloc & Free (from C) - 3 short int *PtrNo = NULL; 4 bytes  * short int PtrNo NULL &1000 PtrNo = (short int *) malloc(1000000* sizeof(short int)); if (PtrNo != NULL) free(PtrNo); I hope you have been taught that you should chase each and every request for dynamic memory with a test to verify that malloc was successful.

Review Malloc & Free (from C) - 4 2 bytes  short int ?? 15298032 &1529803 short int *PtrNo = NULL; 4 bytes  * short int PtrNo NULL &1000 PtrNo = (short int *) malloc(sizeof(short int)); printf("PtrNo = %ld\n\n", PtrNo); if (PtrNo != NULL) free(PtrNo); PtrNo = NULL; Note that when free is called, the compiler does not automatically assign NULL to the value  this should be done by the programmer.

Review Malloc & Free (from C) - 5 2 bytes  short int ?? 15298032 &1529803 short int *PtrNo = NULL; 127 4 bytes  * short int PtrNo NULL &1000 PtrNo = (short int *) malloc(sizeof(short int)); if (PtrNo != NULL) { (*PtrNo) = 127; free(PtrNo); PtrNo = NULL; } Note that when free is called, the compiler does not automatically assign NULL to the value  this should be done by the programmer.

In C++ malloc & free are replaced Bad News In C++ malloc & free are replaced by safer new & delete 26 26

new works just like malloc & delete works just like free safer Good News new works just like malloc & delete works just like free safer You Are To Use delete & new in 2320 27 27

Review New & Delete (from C++) - 1 2 bytes  short int ?? 10165528 &10165528 short int *PtrNo = NULL; 127 4 bytes  * short int PtrNo NULL &1000 PtrNo = new short int; if (PtrNo != NULL) { (*PtrNo) = 127; printf("PtrNo = %ld\n\n", PtrNo); printf("*PtrNo = %hi\n\n", *PtrNo); delete PtrNo; PtrNo = NULL; }

Review New & Delete (from C++) - 1 # define MAX 10 short int *PtrNo = NULL; 20 bytes  10 short int &10165528 ?? 4 bytes  * short int 50 60 70 80 90 10 20 30 40 5 6 7 8 9 1 2 3 4 PtrNo = new short [MAX]; if (PtrNo != NULL) { delete [] PtrNo; PtrNo = NULL; } 10165528 PtrNo NULL &1000 for (int Pos = 0; Pos < MAX; Pos++) PtrNo[Pos] = 10 * Pos; for (int Pos = 0; Pos < MAX; Pos++) cout << setw(5) << PtrNo[Pos];

struct 30 30

NaDa  We Have Not Allocated Any Memory Yet Create A Struct Called Part 24 character Name  long No struct Part { char Name[24]; long No; }; Create Memory Map? NaDa  We Have Not Allocated Any Memory Yet

Create A Dynamic Memory Pointer, Called BB, That Is Of Part Type struct Part { char Name[24]; long No; }; NULL BB &1000 4 bytes  * Part main (int argc, char argv[]) { Part *BB = NULL; Memory Map?

Allocate A Block Of Dynamic Memory For One Part struct Part { char Name[24]; long No; }; main (int argc, char argv[]) Part *BB = NULL; NULL BB &1000 4 bytes  * Part 24 bytes  Part ?? 10165528 &10165528 Name  24 bytes No  4 bytes | Memory Map? BB = new Part;

Place "Basketball" In Part Name struct Part { char Name[24]; long No; }; main (int argc, char argv[]) Part *BB = NULL; BB = new Part; NULL BB &1000 4 bytes  * Part 24 bytes  Part ?? 10165528 &10165528 Name  24 bytes No  4 bytes | Basketball Memory Map? strcpy_s(BB->Name, "Basketball"); or strcpy_s((*BB).Name, "Basketball");

Memory Map? Place 10021 In Part Name struct Part { char Name[24]; long No; }; main (int argc, char argv[]) Part *BB = NULL; BB = new Part; strcpy_s(BB->Name, "Basketball"); NULL BB &1000 4 bytes  * Part 24 bytes  Part ?? 10165528 &10165528 Name  24 bytes No  4 bytes | Basketball 10021 Memory Map? St->No = 10021; or (*St).No = 10021;

Display printf("Name.. = %s\n", BB->Name); struct Part { char Name[24]; long No; }; main (int argc, char argv[]) Part *BB = NULL; BB = new Part; strcpy_s(BB->Name, "Basketball"); (*St).No = 10021; NULL BB &1000 4 bytes  * Part 24 bytes  Part ?? 10165528 &10165528 Name  24 bytes No  4 bytes | Basketball 10021 printf("Name.. = %s\n", BB->Name); printf("No.... = %ld\n\n", (*BB).No); delete BB; }

If You Had This Solution It Would Work  But … I Will Always Take Off A Little If You Don't Test Your Dynamic Memory Processing! 37 37

Always Check Dynamic Memory Allocation! struct Part { char Name[24]; long No; }; main (int argc, char argv[]) { Part *BB = NULL; BB = new Part; if (BB != NULL) { strcpy_s(BB->Name, "Basketball"); (*St).No = 10021; printf("Name.. = %s\n", BB->Name); printf("No.... = %ld\n\n", (*BB).No); delete BB; } }