phy 107 – programming for science. today’s goal learn how arrays normally used in real programs...
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 interchangeablyTRANSCRIPT
LECTURE 29:DYNAMIC MEMORY ALLOCATION
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 = 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
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’;
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
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 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?
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?
First Attempt At Writing Code
Code is simple & easy; what could go wrong?
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;
}
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;
}
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
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;
}
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;
}
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;
}
…& 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 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
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
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 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
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 0th entry in
array SHOULD NOT USE ARRAY after it has been
freed Within program can call free() at any time
Dangling Pointerschar *x = malloc(6 * sizeof(char));strcpy(x, "happy");
Main Memory (RAM)
Dangling Pointerschar *x = malloc(6 * sizeof(char));strcpy(x, "happy");
Main Memory (RAM)
x
Dangling Pointerschar *x = malloc(6 * sizeof(char));strcpy(x, "happy");char *ptr = x;
Main Memory (RAM)
x
Dangling Pointerschar *x = malloc(6 * sizeof(char));strcpy(x, "happy");char *ptr = x;
Main Memory (RAM)
x
ptr
Dangling Pointerschar *x = malloc(6 * sizeof(char));strcpy(x, "happy");char *ptr = x;free(x);
Main Memory (RAM)
x
ptr
Dangling Pointerschar *x = malloc(6 * sizeof(char));strcpy(x, "happy");char *ptr = x;free(x);
Main Memory (RAM)
x ptr
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
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
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
Not Always A Laughing Matter
Your Turn
Get into your groups and try this assignment
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