230 likes | 404 Views
CS 210 Lecture 3 : Dynamic memory and pointers. Data Structures. Why Dynamic Memory Allocation?. No need to know in advance the size of the data structure. No memory needlessly allocated. Your limit is the computer ’ s memory limit. Automatic objects E.g. int i; float j;
E N D
CS 210Lecture 3 : Dynamic memory and pointers Data Structures CS 210
Why Dynamic Memory Allocation? • No need to know in advance the size of the data structure. • No memory needlessly allocated. • Your limit is the computer’s memory limit. CS 210
Automatic objects E.g. int i; float j; Space allocated during compile time and will remain as long as object is within scope. Compiler de-allocates space as soon as object goes out of scope. Dynamic objects Objects not assigned name while program is written and thus are only accessible via pointers. Allocation/de-allocation entirely managed by the programmer and is performed during runtime. Automatic Vs. Dynamic Objects CS 210
Declaring a pointer • A pointer is a variable that can store the memory address of some piece of data. • Declaring a pointer: float *p; • p is a pointer that can store a memory address of a floating point variable. CS 210
Allocating memory Declaring a pointer does not automatically give it a valid memory address: float *p; To allocate memory, use the key word: new p = new float; This is dynamic allocation of memory. p p ? CS 210
Heap p 1000 1000 1001 1001 p 1002 1002 1003 1003 1004 Heap 1004 . . . 2000 . . . 2000 The Memory Heap C++ maintains a storage pool of available memory called the heap. The keyword new allocates memory from this storage pool. p = new float; CS 210
Returning memory to the heap • Use the keyword, delete, to return memory to the heap: • delete p; • p no longer points to a valid memory location (p is now undefined) • The memory is returned to the heap and can be reallocated later. • After deleting a pointer, it should always be reset to NULL. CS 210
De-referencing Pointers To access the memory pointed to by a pointer, use the indirection operator (*): *p = 15.5; Example: float *p; p = new float; *p = 15.5; cout << "The contents of memory cell pointed to by p is " << *p << endl; delete p; p 15.5 CS 210
Watch Out! Dereferencing un initialized pointers not only may alter other important data, or even destroy some other parts of memory, but even worst, this type of accidental error may run silently without causing any compilation or runtime errors that might signal it. So, it is a difficult-to-find error. int *random_pointer; CS 210
General form for pointers Declaration of a pointer: type *pointerName; Allocation of memory: new type or new type[n] //allocates n elements of specified type Accessing data with pointer: *pointerName CS 210
Illegal Pointer operations Because pointers hold addresses, you cannot assign data of type int or float or other data types to a pointer. The following is not allowed: int *p; float *q; p = 1000; // Not Allowed q = 15.5; // Not Allowed CS 210
Assigning a pointer One pointer can be assigned to another of the same type: int *p; int *q; p = new int; q = p; *p = 20; cout << *p << " " << *q << endl; p 20 q CS 210
Recall Arrays int numbers[5]; • The name of the array, numbers, contains the base address of the array. • numbers, is a pointer. CS 210
Dynamically Allocated Arrays int size,* dynamic_array, i; cout<<“Enter an array size: “<< flush; cin>> size; dynamic_array= new int [size]; for (i=0;i<size; i++) dynamic_array[i]=i; delete []dynamic_array; CS 210
Pointer arithmetic Pointer arithmetic allows accessing of items in an array: int *p, *q; p = new int[5]; q=p+2; q++; *p is value of p[0] *(p+i) is value of p[i] Each increment of p moves the pointer by enough memory to move to next item in the array. CS 210
Addresses of automatic objects • Pointer variables can be used to access automatic objects as well. • This creates an alias for the automatic variable and should be carefully managed, even better, avoided. • Example: char alpha; char *char_ptr; char_ptr = & alph; alpha alpha char_ptr CS 210
Pointers to structs Pointers to structs follow the same rules: struct money { int dollars; int cents; }; money *p; p = new money; dollars cents p ? ? CS 210
Accessing struct members Struct members are accessed with the selection operator: p = new money; (*p) . dollars = 10000; //The parentheses are essential! (*p) . cents = 50; Alternatively: p -> dollars = 10000; p -> cents = 50; dollars cents p 10000 50 CS 210
orphan structs If you assign one pointer to another, the struct previously pointed to by the latter is no longer accessible: Consider p and q: dollars cents p 6947 25 dollars cents q 6947 40 CS 210
orphan structs If you assign one pointer to another, the struct previously pointed to by the latter is no longer accessible: q = p; dollars cents p 6947 25 dollars cents q 6947 40 CS 210
Things to be careful about WARNINGS: • If more than one pointer points to the same structure, if one is deleted, the other may still point to that location. However, C++ may reassign that memory, causing errors in the program execution. • Make sure you no longer need a structure before you return it to the heap. • Only use delete with pointers whose values were set by new. CS 210
Diagram each line struct electric { String20 current; int volts; }; electric *p, *q; p = new electric; strcpy( p - > current, "AC" ); p - > volts = 220; q = new electric; q -> volts = p - > volts; strcpy ( q - > current, "DC"); CS 210
Diagram the pointers electric *a, *b, *c; a = new electric; b = new electric; c = new electric; a = b; b = c; c = a; CS 210