Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 PHY 107 – Programming For Science

2 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

3 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

4 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’;

5 Pointers Can Be NULL

6 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

7 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

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

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

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

11 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; }

12 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; }

13 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; }

14 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; }

15 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; }

16 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; }

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

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

19 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

20 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

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

22 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

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

24 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

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

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

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

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

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

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

31 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

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

33 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

34

35 Not Always A Laughing Matter

36 Your Turn  Get into your groups and try this assignment

37 For Next Lecture


Download ppt "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."

Similar presentations


Ads by Google