Upload
sherman-smith
View
215
Download
0
Tags:
Embed Size (px)
Citation preview
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 new & delete
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 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 == if (pointer != NULL)…
To use NULL, several rules must be followed Cannot use null, Null, or nuLL, name must
be in CAPS #include <cstring> 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 file to make updates
easy By writing software in 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 1st line of file to use
declaring arrays Know that in the future may not want
files Databases can be faster, but also more
expensive Read from files using function so easy to
change 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 1st line of file to use
declaring arrays Know that in the future may not want
files Databases can be faster, but also more
expensive Read from files using function so easy to
change later
Code is simple & easy; what could go wrong?
First Try At Code
double[] readCosts(int & nItems) {// Open the fileifstream fIn(“moolah.txt”);// Read in the number of items & create the arrayfIn >> 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;
}
Compile In MS Visual C++...
double[] readCosts(int & nItems) {// Open the fileifstream fIn(“moolah.txt”);// Read in the number of items & create the arrayfIn >> 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;
}
Compile In MS Visual C++...
double[] readCosts(int & nItems) {// Open the fileifstream fIn(“moolah.txt”);// Read in the number of items & create the arrayfIn >> 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
Move to Eclipse + Mac OS
double[] readCosts(int & nItems) {// Open the fileifstream fIn(“moolah.txt”);// Read in the number of items & create the arrayfIn >> 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;
}
Compiles on Eclipse + Mac OS…double[] readCosts(int & nItems) {
// Open the fileifstream fIn(“moolah.txt”);// Read in the number of items & create the arrayfIn >> 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;
}
…& 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 Memory shared with important data
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 Memory shared with important data
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 Array entries 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 = new int[100];char * cstring;double * ddd;int * arr;const int FOUR = 5;int val;cin >> val;cstring = new char[10];ddd = new double [FOUR – 1 + 2];arr = new int[val];arr[2] = 23;long * pirate = new int[arr[2]];
All Done Now
After being allocated, may not need array Normal arrays will “die” once they go out of
scope Unfortunately, dynamic arrays must be
killed Else system runs slower & slower as
memory filled If memory is completely full, program can
crash delete [] frees dynamically allocated
array Need to use with address of 0th entry in
array CANNOT USE ARRAY once it has been
deleted Delete can occur anywhere in any function
Dangling Pointers
char *x = new char[6];strcpy(x, "happy");char *ptr = x;delete [] x;
Main Memory (RAM)
x
ptr
Dangling Pointers
char *x = new char[6];strcpy(x, "happy");char *ptr = x;delete [] x;
Main Memory (RAM)
x ptr
Dangling Pointers
char *x = new char[6];strcpy(x, "happy");char *ptr = x;delete [] x; // But I’m not dead yet!
Main Memory (RAM)
ptr
Dangling Pointers
char *x = new char[6];strcpy(x, "happy");char *ptr = x;delete [] x; // But I’m not dead yet!char *y = new char[6];strcpy(y, "sad");cout << ptr << endl; // oops…
Main Memory (RAM)
y ptr
Dangling Pointers
char *x = new char[6];strcpy(x, "happy");char *ptr = x;delete [] x; // But I’m not dead yet!char *y = new char[6];strcpy(y, "sad");cout << ptr << endl; // oops…
Hard-to-find bugs created throughout code