PHY 107 – Programming For Science. Today’s Goal  Learn how arrays normally used in real programs  Why a function returning an array causes bugs  How.

Slides:



Advertisements
Similar presentations
Chapter 9 Pointers and Dynamic Arrays. Overview 9.1 Pointers 9.2 Dynamic Arrays.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
Kernighan/Ritchie: Kelley/Pohl:
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.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
Dynamic Memory Allocation in C++. Memory Segments in C++ Memory is divided in certain segments – Code Segment Stores application code – Data Segment Holds.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
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.
CEG 221 Lesson 2: Homogeneous Data Types Mr. David Lippa.
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.
CSC 107 – Programming For Science. Today’s Goal  Learn how pointers really used with arrays  Exploit the similarity between pointers & arrays  Take.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
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.
CSC 107 – Programming For Science. Today’s Goal  Learn relationship between pointers & arrays  How and why they both are similar  Take advantage of.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Outline Midterm results Static variables Memory model
CS50 SECTION: WEEK 4 Kenny Yu. Announcements  Problem Set 4 Walkthrough online  Problem Set 2 Feedback has been sent out  CORRECTION: Expect all future.
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.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dynamic Memory Allocation 9.8.
Pointers and Arrays Beyond Chapter Pointers and Arrays What are the real differences? Pointer Holds the address of a variable Can be pointed.
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.
Stack and Heap Memory Stack resident variables include:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
CSC 107 – Programming For Science. Today’s Goal Variables  Variable  Variable name location to store data  Only for humans; 0 x 7E8A2410 harder to.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
CSC 107 – Programming For Science. Today’s Goal  Learn how pointers really used with arrays  Exploit the similarity between pointers & arrays  Take.
CSC 107 – Programming For Science. Today’s Goal  When lecture over, start understanding pointers  What a pointer is and what it is not  Why pointers.
CSC 107 – Programming For Science. Today’s Goal  When lecture over, start understanding pointers  What a pointer is and what it is not  Why pointers.
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.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
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.
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.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Copyright © – Curt Hill Pointers A Light Introduction.
ECE Application Programming
Pointers *, &, array similarities, functions, sizeof.
© 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.
CSC Programming for Science Lecture 34: Dynamic Pointers.
PHY 107 – Programming For Science. Today’s Goal  Discuss how to hand data to functions  Review loopholes in variables & scoping rules  Ways to get.
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.
CSC 107 – Programming For Science. Today’s Goal  Discover best uses of structures in a program  How we can mix pointers inside structures  Assigning.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
CSE 220 – C Programming malloc, calloc, realloc.
Dynamic Storage Allocation
Memory allocation & parameter passing
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
Stack and Heap Memory Stack resident variables include:
Chapter 15 Pointers, Dynamic Data, and Reference Types
Memory Allocation CS 217.
EECE.2160 ECE Application Programming
Pointers and Arrays Beyond Chapter 16
C Programming Lecture-8 Pointers and Memory Management
SPL – PS2 C++ Memory Handling.
Presentation transcript:

PHY 107 – Programming For Science

Today’s Goal  Learn how arrays normally used in real programs  Why a function returning an array causes bugs  How to declare array if size varies with each run  Using (& fixing problems) with malloc & free  All doing great, but pointers still hard

Arrays vs. Pointers Arrays = YamsPointers = Sweet Potatoes  Makes space at declaration  Variable value is address  Use [] to access entries  Can also access using *  Can be assigned a pointer  Needs target to be useful  Variable value is address  Use * to access target  Can also access using []  Can be assigned array Often use pointers & arrays interchangeably

Use Like ArrayUse Like Pointer Arrays + Pointers = char array[100]; char * ptr = array; *array = ‘E’; *(ptr + 1) = ‘q’; *(ptr + 2) = ‘u’; *(array + 3) = ‘a’; *(ptr + 4) = ‘l’; *(array + 5) = ‘\0’; char array[100]; char * ptr = array; array[0] = ‘E’; ptr[1] = ‘q’; ptr[2] = ‘u’; array[3] = ‘a’; ptr[4] = ‘l’; array[5] = ‘\0’;

Pointers Can Be NULL

Starting a New Company  Developing software for your new company  Website selling engineering gear of all possible types  Plans to grow site to offer consulting & other services  Being as big as Amazon.com is your eventual goal  But, for the moment, your company is very small

Developing the Software  Want to write code that scales with company  Read inventory from user to make updates easy  By writing software in C/C++, can port to new machines  No hard limits (if possible) since guesses will be wrong

First Attempt At Writing Code  Use 2 arrays: one for names and one for costs  Work in parallel, so item data at same index in arrays  Number of items entered 1 st to size declared arrays  Know that in the future will not want to type  Databases can be faster, but also more expensive  Put initial I/O in function so easy to update later  Code is simple & easy  Code is simple & easy; what could go wrong?

First Attempt At Writing Code  Use 2 arrays: one for names and one for costs  Work in parallel, so item data at same index in arrays  Number of items entered 1 st to size declared arrays  Know that in the future will not want to type  Databases can be faster, but also more expensive  Put initial I/O in function so easy to update later  Code is simple & easy  Code is simple & easy; what could go wrong?

First Attempt At Writing Code  Code is simple & easy  Code is simple & easy; what could go wrong?

First Try At Code double[] readCosts(int *nItems) { // Read in the number of items & create the array scanf(“%d\n”, nItems); double costs[*nItems]; // Now read the cost of each item from the file for (int i = 0; i < *nItems; i++) { scanf(“%lf\n”, &costs[i]); } // And return the array… return costs; }

Compile In MS Visual C++... double[] readCosts(int *nItems) { // Read in the number of items & create the array scanf(“%d\n”, nItems); double costs[*nItems]; // Now read the cost of each item from the file for (int i = 0; i < *nItems; i++) { scanf(“%lf\n”, &costs[i]); } // And return the array… return costs; }

Compile In MS Visual C++... double[] readCosts(int *nItems) { // Read in the number of items & create the array scanf(“%d\n”, nItems); double costs[*nItems]; // Now read the cost of each item from the file for (int i = 0; i > costs[i]; } // And return the array… return costs; }

Compile on Eclipse + Mac OS… double[] readCosts(int *nItems) { // Read in the number of items & create the array scanf(“%d\n”, nItems); double costs[*nItems]; // Now read the cost of each item from the file for (int i = 0; i < *nItems; i++) { scanf(“%lf\n”, &costs[i]); } // And return the array… return costs; }

Move to Eclipse + Mac OS double[] readCosts(int *nItems) { // Read in the number of items & create the array scanf(“%d\n”, nItems); double costs[*nItems]; // Now read the cost of each item from the file for (int i = 0; i < *nItems; i++) { scanf(“%lf\n”, &costs[i]); } // And return the array… return costs; }

Compiles on Eclipse + Mac OS… double[] readCosts(int *nItems) { // Read in the number of items & create the array scanf(“%d\n”, nItems); double costs[*nItems]; // Now read the cost of each item from the file for (int i = 0; i < *nItems; i++) { scanf(“%lf\n”, &costs[i]); } // And return the array… return costs; }

…& Crashes on Eclipse + Mac OS  Program behaves oddly without clear reasons  During program value of variables just change  Prices go up and down for no clear reason  At some bizarre time, program eventually crashes

…& Crashes on Eclipse + Mac OS  Program behaves oddly without clear reasons  During program value of variables just change  Prices go up and down for no clear reason  At some bizarre time, program eventually crashes

How To Write Buggy Programs  Unsafe to return  Unsafe to return array declared in function  Know how we draw boxes when we call function  Cross out box at end of that call to the function boxes really exist  Guess what? Those boxes really exist in memory  Within box are declared arrays’ memory locations!  Array uses the same address as other things  Odd behavior results as overwrite each other’s values  Important data held in shared memory

How To Write Buggy Programs  Unsafe to return  Unsafe to return array declared in function  Know how we draw boxes when we call function  Cross out box at end of that call to the function boxes really exist  Guess what? Those boxes really exist in memory  Within box are declared arrays’ memory locations!  Array uses the same address as other things  Odd behavior results as overwrite each other’s values  Important data held in shared memory

What To Do?  Do not want to have to declare array in main  Lots of rewrites needed if we do file I/O in main  Do not have money for huge array would need later  Cannot declare in function without risk of crash  How to make long-lived or variable-length arrays?

Dynamic Storage Allocation!  Way of allocating arrays in own memory space  No limits on space – array can be any (integer) size  Type must match variable, but no new restrictions  Memory reserved until explicitly returned to system NOT  Entries NOT initialized to 0 when array allocated  Once it is allocated, use like normal array  Cannot tell difference given two valid arrays  Passing as parameter or returning from function okay

Dynamic Storage Allocation malloc() malloc() malloc() malloc() malloc() int * ptr = malloc(100 * sizeof(int)); char * cstring; double * ddd; int * arr; const int FOUR = 5; int val; scanf(“%d”, &val); cstring = malloc(10 * sizeof(char)); ddd = malloc((FOUR-1+2) * sizeof(double)); arr = malloc(val* sizeof(int)); arr[2] = 23; long * pirate = malloc(arr[2]*sizeof(long));

All Done Now  After being allocated, may not need array  Normal arrays “die” when frame is crossed out  Not a problem here: dynamic arrays must be killed  Otherwise live forever, slowing system as it runs  If memory is completely full, program can crash  free(varName) dynamically allocated array  Argument must be address of 0 th entry in array  SHOULD  SHOULD NOT USE ARRAY after it has been freed  Within program can call free() at any time

Dangling Pointers char *x = malloc(6 * sizeof(char)); strcpy(x, "happy"); Main Memory (RAM)

Dangling Pointers char *x = malloc(6 * sizeof(char)); strcpy(x, "happy"); Main Memory (RAM) x

Dangling Pointers char *x = malloc(6 * sizeof(char)); strcpy(x, "happy"); char *ptr = x; Main Memory (RAM) x

Dangling Pointers char *x = malloc(6 * sizeof(char)); strcpy(x, "happy"); char *ptr = x; Main Memory (RAM) x ptr

Dangling Pointers char *x = malloc(6 * sizeof(char)); strcpy(x, "happy"); char *ptr = x; free(x); Main Memory (RAM) x ptr

Dangling Pointers char *x = malloc(6 * sizeof(char)); strcpy(x, "happy"); char *ptr = x; free(x); Main Memory (RAM) x ptr

Dangling Pointers char *x = malloc(6 * sizeof(char)); strcpy(x, "happy"); char *ptr = x; free(x); // But I’m not dead yet! Main Memory (RAM) ptr

Dangling Pointers char *x = malloc(6 * sizeof(char)); strcpy(x, "happy"); char *ptr = x; free(x); // But I’m not dead yet! char *y = malloc(6 * sizeof(char)); strcpy(y, "sad"); printf(“%s\n”, ptr); // oops… Main Memory (RAM) y ptr 

Dangling Pointers char *x = malloc(6 * sizeof(char)); strcpy(x, "happy"); char *ptr = x; free(x); // But I’m not dead yet! char *y = malloc(6 * sizeof(char)); strcpy(y, "sad"); printf(“%s\n”, ptr); // oops…  Hard-to-find bugs created throughout code

Not Always A Laughing Matter

Your Turn  Get into your groups and try this assignment

For Next Lecture