cse 143
play

CSE 143 Whats wrong with the way things are? One problem: All of - PDF document

CSE 143 Whats wrong with the way things are? One problem: All of our data structures so far have a maximum size. Dynamic Memory E.g. arrays declared with fixed size This size is fixed at compile time . Sometimes this is


  1. CSE 143 What’s wrong with the way things are? • One problem: All of our data structures so far have a “maximum” size. Dynamic Memory • E.g. arrays declared with fixed size • This size is fixed at compile time . • Sometimes this is acceptable, sometimes not • Allocate too little: application may not run [Chapter 4, pp. 148-157, 172-177] • Allocate too much: wasted memory (may run out) • Many real applications need to grow and shrink the amount of memory consumed by an object during execution (runtime). 07/06/01 07/06/01 J-1 J-2 A "Shape" Problem Solution: "Dynamic" Memory • All of our data structures so far are fixed in form • 1. Allow some of the memory to be allocated as and shape needed • Individual vars, structs, classes, or arrays of them, or • 2. Allow pieces of memory (variables) to be linked simple nesting in arbitrarily complex ways • Many problems require more creative shapes • Most languages provide some form of dynamic • Family tree memory. • Company database • C++ provides an interface to dynamic memory via • Recursive data, complex links two new operators: new and delete . • Needed variety • The dynamic memory is accessed through pointers. • for modeling the data • for efficiency 07/06/01 07/06/01 J-3 J-4 Plan of Study Data and Memory • First • Objects of different types use differing amounts of memory • Review pointers and reference parameters • Next • Built-in types: implementation dependent • PC (typical): • Introduce C++ new and delete operators char: 1 byte (8 bits) • Dangers! "wide" chars: 2 bytes (for international UNICODE) • Dynamic memory in classes int: typically 4 bytes • Pointers vs. arrays • 2 bytes on older systems • up to 8 bytes on newest "64-bit" computers • Dynamic linked lists double: 8 bytes on many systems • Finally... • Programmer defined types (such as classes) • Even more about dynamic memory in classes • depends on size of data members • Vector class revisited • could be few bytes or thousands of bytes 07/06/01 07/06/01 J-5 J-6 CSE 143 J

  2. Ways of Using Memory Pointer Variables • By "address of an object" we mean the address of • Static - allocated at program startup time, exists the first memory cell used by the object throughout the execution of the entire program • A pointer variable is one that contains the address • Best-known example: global variables of another data object as its value. • Automatic - implicitly allocated upon function • To declare a pointer variable or parameter: entry, deallocated on exit Type* name; void foo ( char x ) { int temp ; • Example: . . . // x and temp are deallocated here int* intPtr; } char* charPtr; • Dynamic - explicitly allocated and deallocated by BigNat* bigNatPtr; the programmer 07/06/01 07/06/01 J-7 J-8 Review: Swap in C Two Important Operators • In CSE 142, you used pointers to write functions • The address-of operator &: which modified their arguments: int x = 45; int* p = &x; • The dereference operator *: void swap(int* p, int* q) { *p = 30; int temp; p = 72; // what’s the problem here? temp = *p; *p = *q; Note: The & symbol used to declare reference parameters *q = temp; is the same keyboard character, but it means something } quite different in that context // example call: swap(&intOne, &intTwo); // don’t forget the & 07/06/01 07/06/01 J-9 J-10 Review: Swap in C++ Reference Types • C++ lets us use reference parameters, leading to • Main use: parameters cleaner code: • We can also declare variables of reference types: Type& rname //rname will hold an alias to something //of type Type void swap(int& a, int& b) { • Example: int temp = a; int x; a = b; int& refx = x; // a ref. variable must be initialized b = temp; } x = 40; cout << refx; // what’s the output? refx = 20; // example call: cout << x; // what’s the output? swap(intOne, intTwo); // note: no & • In 143 we will avoid stand-alone reference variables • but reference parameters are used as needed. 07/06/01 07/06/01 J-11 J-12 CSE 143 J

  3. Pointers and Types C++ Is "Strongly Typed" • Pointers to different types themselves are int i; int * ip; different types double x; double * xp; double *dpt; ... BankAccount * bp; x = i; /* no problem */ i = x; /* not recommended */ • C/C++ considers dpt and bp to have different types ip = 30; /* No way */ • even though under the hood they are both just memory ip = i; /* Nope */ addresses ip = &i; /* just fine */ • Types have to match in many contexts ip = &x; /* forget it! */ &i = ip; /* meaningless */ • e.g. actual param types matching formal param types • pointers are no exceptions 07/06/01 07/06/01 J-13 J-14 The NULL pointer Pointers as Types • During program execution, a pointer variable can • Domain (possible values) be in one of the following states: • The set of all memory addresses along with the NULL pointer • Unassigned (uninitialized) • Some operations are valid on pointers of all types. • Pointing to a data object We’ll cover only a subset: • Contain the special value NULL (can also use 0) = (assignment) • The constant NULL is defined in <cstddef> int* p = &someInt; (stddef.h), and is used to mean "a pointer that * (dereference) does not point to any object.“ *p = 345; • Defined to be 0 == (equality test) • It does not mean "address 0 of the computer" if (ptr1 == ptr2) { . . . } //Carefull!! What is being compared? • NULL is compatible with all pointer types 07/06/01 07/06/01 J-15 J-16 More Pointer Operations new : Allocating Memory != (test for inequality) • Allocate dynamic memory with the new operator: if (ptr1 != ptr2) { . . . } • The expression new Type returns a pointer to a newly created object of type Type : delete (deallocate) int *p, *p2; delete ptr; // more on this later p = new int; // allocate a single int *p = 2001; -> (select a member of a pointed-to object) p2 = new int[10]; // allocate an array of ints p2[0] = -17; // can use array notation with ptrs void foo (BankAccount* b) { • The memory allocated will be the right size for the b->printBalance(); type of object } // How would you write this if -> were not available? • The pointer contains the address of the beginning of that area of memory. 07/06/01 07/06/01 J-17 J-18 CSE 143 J

  4. new Could Fail! Deallocation int * bigP = new int [1000000]; • Deallocate memory with the delete operator: • delete Pointer deallocates the object pointed to by Pointer • new returns NULL if the memory could not be delete p; // deallocating a simple object allocated (or throws an exception in newer delete [] str; // deallocating an array of objects versions of C++) • The proper amount of memory is released • Advice: always test result • Delete does not alter the bits in the pointer! • Assert is simple: • Useful habit: int * bigP = new int [1000000]; delete p; // p not changed p = NULL; assert (bigP != NULL); • The memory MUST have been allocated via new • or make a test before using: • Woe if you try to delete local memory, etc. if (bigP != NULL) ... // go ahead and use the pointer • Disaster if you use delete instead of delete[ ] or vice versa else ... // take some recovery action 07/06/01 07/06/01 J-19 J-20 Heap Memory Where does the memory come from? heap • Objects created by new come from a region of local memory set aside for dynamic objects int *v, *w; v = new int; • Sometimes called the heap , or free store w = new int[5]; • Textbook doesn’t use those names BA *pBA; • The new operator obtains a chunk of memory pBA = new BA; from the heap; delete returns that memory to the delete v; heap. delete [] w; • In C++ the programmer must manage the heap. delete pBA; • Dynamic memory is unnamed and can only be accessed through pointers. 07/06/01 07/06/01 J-21 J-22 Dynamic Memory: Review So Far Dynamic Memory Is Dangerous • new gets memory, delete gives it back • A major source of program bugs • Memory leaks: not giving back allocated memory • In all cases: The new operator returns a pointer to an object. • Dangling pointers: using a pointer to memory no longer allocated • Unless new fails -- then returns NULL (or throws an may silently clobber data exception, which probably terminates the program) • Using uninitialized pointers • The memory is on the heap may silently clobber data • unlike local variables, which are in the activation record • Security violations: giving client access to private data (stack frame) • These are run-time errors • Compiler can’t catch them • The program may appear to run correctly... sometimes 07/06/01 07/06/01 J-23 J-24 CSE 143 J

Recommend


More recommend