phy 107 – programming for science. today’s goal learn how arrays normally used in real programs...

37
LECTURE 29: DYNAMIC MEMORY ALLOCATION PHY 107 – Programming For Science

Upload: rosemary-beasley

Post on 17-Jan-2018

217 views

Category:

Documents


0 download

DESCRIPTION

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

TRANSCRIPT

Page 1: 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

LECTURE 29:DYNAMIC MEMORY ALLOCATION

PHY 107 – Programming For Science

Page 2: 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

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

Page 3: 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

Arrays vs. Pointers

Arrays = Yams Pointers = 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 arrayOften use pointers & arrays interchangeably

Page 4: 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

Use Like Array Use 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’;

Page 5: 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

Pointers Can Be NULL

If pointer has no target, need a special value Not an actual address – NULL shows lack of

address No relation to null character – names are

coincidence If pointer is NULL, accessing value

causes crash Check for NULL before using unknown

pointer Check using equality: if (pointer != NULL)

To use NULL, several rules must be followed Cannot use null, Null, or nuLL; name must

be in CAPS #include <stdio.h> needed at program

start

Page 6: 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

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

Page 7: 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

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

Page 8: 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

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 1st 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; what could go wrong?

Page 9: 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

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 1st 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; what could go wrong?

Page 10: 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

First Attempt At Writing Code

Code is simple & easy; what could go wrong?

Page 11: 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

First Try At Code

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

}

Page 12: 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

Compile In MS Visual C++...

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

}

Page 13: 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

Compile In MS Visual C++...

double[] readCosts(int *nItems) {// Read in the number of items & create the arrayscanf(“%d\n”, nItems);double costs[*nItems];// Now read the cost of each item from the filefor (int i = 0; i < nItems; i++) { fIn >> costs[i];}// And return the array…return costs;

}

Oops!Some compilers will allow this, but C++ standard requires that array lengths must be literal or constant

Page 14: 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

Compile on Eclipse + Mac OS…double[] readCosts(int *nItems) {

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

}

Page 15: 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

Move to Eclipse + Mac OS

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

}

Page 16: 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

Compiles on Eclipse + Mac OS…double[] readCosts(int *nItems) {

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

}

Page 17: 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

…& 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

Page 18: 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

…& 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

Page 19: 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

How To Write Buggy Programs

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 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

Page 20: 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

How To Write Buggy Programs

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 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

Page 21: 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

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?

Page 22: 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

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 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

Page 23: 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

Dynamic Storage Allocation

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));

Page 24: 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

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 0th entry in

array SHOULD NOT USE ARRAY after it has been

freed Within program can call free() at any time

Page 25: 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

Dangling Pointerschar *x = malloc(6 * sizeof(char));strcpy(x, "happy");

Main Memory (RAM)

Page 26: 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

Dangling Pointerschar *x = malloc(6 * sizeof(char));strcpy(x, "happy");

Main Memory (RAM)

x

Page 27: 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

Dangling Pointerschar *x = malloc(6 * sizeof(char));strcpy(x, "happy");char *ptr = x;

Main Memory (RAM)

x

Page 28: 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

Dangling Pointerschar *x = malloc(6 * sizeof(char));strcpy(x, "happy");char *ptr = x;

Main Memory (RAM)

x

ptr

Page 29: 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

Dangling Pointerschar *x = malloc(6 * sizeof(char));strcpy(x, "happy");char *ptr = x;free(x);

Main Memory (RAM)

x

ptr

Page 30: 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

Dangling Pointerschar *x = malloc(6 * sizeof(char));strcpy(x, "happy");char *ptr = x;free(x);

Main Memory (RAM)

x ptr

Page 31: 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

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

Main Memory (RAM)

ptr

Page 32: 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

Dangling Pointerschar *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

Page 33: 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

Dangling Pointerschar *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

Page 34: 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
Page 35: 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

Not Always A Laughing Matter

Page 36: 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

Your Turn

Get into your groups and try this assignment

Page 37: 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

For Next Lecture

Review of pointers in class on Wednesday What questions do you have about how

they work? Are you ready to use & trace them in

programs? Create and delete pointers during program

running?

For Tuesday, D2L has Week #10 assignment

Midterm #2 in class on Friday