280 likes | 419 Views
CMPT 128: Introduction to Computing Science for Engineering Students. Pointers. Dynamic and Automatic Variables. Dynamic variables Created during program execution Destroyed during program execution Must remember to destroy all dynamic variable created Automatic variables
E N D
CMPT 128: Introduction to Computing Science for Engineering Students Pointers
Dynamic and Automatic Variables • Dynamic variables • Created during program execution • Destroyed during program execution • Must remember to destroy all dynamic variable created • Automatic variables • Declared within function definition • Not dynamic • Automatically created when function is called • Automatically destroyed when function call completes • Function scope local variables are an example
Dynamic variables: creation • C++ • Use the keyword new myVariablePointer = new int; • Variable can only be referenced using the pointer myVariablePointer • Variable does not have an identifier (name)
Dynamic variables: creation • C • Use function malloc() int *myVariablePointer; myVariablePointer = (int *)malloc( sizeof(int) ); • Variable can only be referenced using the pointer myVariablePointer • Variable does not have an identifier (name)
Dynamic variables: destruction • If you allocate dynamically allocate a variable you must also destroy it after you are finished it. • We will discuss how to destroy variables later.
Initializing pointers • After you declare a pointer double *v1p, v1, *v2p, *v3p; • It is good programming practice to initialize the pointer to NULL or some other particular value. v1p = (double *)malloc( sizeof(double) ); v3p = new int; • Now consider the new (C++) and malloc() (C)
Making dynamic variables • When you declare an automatic variable you provide an identifier and memory is allocated for the variable that will be referred to by that identifier • You can make dynamic variables during the execution of your program. These dynamic variables can be referred to by only a reference, no identifier is necessary
C++ Using the new Operator • Operator new dynamically creates variables of any type, for example v3p = new int; • creates a new integer variable • Value of expression ( new int ) is a pointer to the new variable. • The new variable has no identifier • The pointer to the new variable is assigned to (placed in) pointer to integer variable v3p.
Pointers in assignment statements • int *v3p; • v3p = new int; Value of pointer variable Pointer Identifier v3p ? Variable Value address Value of pointer variable Variable Identifier Pointer Identifier v3p 1004 1004 ?
Pointers in assignment statements • int *v3p; • v3p = new int(77); Value of pointer variable Pointer Identifier v3p ? Variable Value address Value of pointer variable Variable Identifier Pointer Identifier v3p 1004 1004 77
C Using malloc() • Operator new dynamically creates variables of any type, for example v3p = (int*)malloc(sizeof(int)); • creates a new integer variable • Function malloc returns a void pointer to the new variable. You cast the pointer • The new variable has no identifier • The pointer to the new variable is assigned to (placed in) pointer to integer variable v3p.
Pointers in assignment statements • int *v3p; • v3p = (int*)malloc(sizeof(int)); Value of pointer variable Pointer Identifier v3p ? Variable Value address Value of pointer variable Variable Identifier Pointer Identifier v3p 1004 1004 ?
Other examples of ‘new’ int *ap=NULL; double *bp=NULL; double*dp = NULL; char *cp = NULL; ap= new int; bp= new double; cp= new char[23]; dp= new double[100];
Other examples of malloc() int *ap=NULL; double *bp=NULL; double *dp = NULL; char *cp = NULL; ap = (int *)malloc( sizeof(int)); bp= (double *)malloc(sizeof(double)); cp = (char *)malloc( 23*sizeof(char)); dp= (double *)malloc( 100*sizeof(double));
Memory Management • Heap memory or freestore memory • Reserved for dynamically-allocated variables • All new dynamic variables consume heap memory • Possible to consume all heap memory • If all heap memory is consumed further allocations of dynamic variables using will fail • interaction with your computer’s virtual memory system may cause unexpected behavior • Your program may not know when heap is exhausted
new Success – New Compiler • Compilers following standards after 2002: • If new operation fails: • Program terminates automatically • Produces error message • Can still make your program continue after a failed allocation by • Catching the exception (more later) • Using a modified version of the NULL check
Checking new Success • Can still test if null returned by call to new: int *p;p = new(nothrow) int;if (p == NULL){cout << "Error: Insufficient memory.\n"; // exit if this is a critical allocation // otherwise continue }
Checking malloc() Success • Can still test if null returned by call to new: int *p = NULL;p = (int*)malloc(sizeof(int));if (p == NULL){cout << "Error: Insufficient memory.\n"; // exit if this is a critical allocation // otherwise continue }
Memory management • We have seen half of the tools needed for memory management in C++ • We can create variables dynamically • The other half is to be able to destroy the dynamic variables we have created after we are done with them. • Destroying variables we have created is our responsibility, must assure that all dynamically allocated variables are destroyed so that the memory allocated to them can be returned to the heap • To destroy dynamically allocated variables use the delete operator
C++ delete Operator • De-allocate dynamic memory • Returns memory to the heap • Example: int *v1p;p = new int(5);… //Some processing…delete p;
C free() Function • De-allocate dynamic memory • Returns memory to the heap • Example: int *p;p = (int *)malloc( sizeof(int) ); *p = 5;… //Some processing…free(p);
C++ delete Operator • De-allocate dynamic memory • Returns memory to the heap • Example: int *p;p = new int[5];… //Some processing…delete [ ] p;
C free() Function • De-allocate dynamic memory • Returns memory to the heap • Example: int *p;p = (int *)malloc( 5* sizeof(int) );… //Some processing…free(p);
Potential problems • It is possible to • Try to access memory you have already deleted: • Lose all references to a piece of memory and be prevented from deleting that memory • Means the heap is reduced in size for the rest or your program and for other programs run after your program completes. • Memory that is dynamically allocated but not deleted may not be returned to heap
Memory Leaks • Beware; do not loose your last reference to memory thatwasallocated using new or malloc() 88 All reference to this memory has been lost. It is assigned to the program but cannot be used or deleted. It has 'leaked' from memory management within the program. Available heap has been decreased. v1p v2p 53 v2p = new int; v2p = (int *)malloc(sizeof(int)); 88 v1p v2p 53 23
C++ Dangling Pointers • delete p; // terminate allocation of memory // pointed to by p • The program no longer owns the memory pointed to by p but p still points to that memory • p is now a dangling pointer • If p is dereferenced ( *p ) results are not predictable • Avoid dangling pointers • Assign pointer to NULL after delete:delete p; // p still points to the previously allocated memoryp = NULL; // p now points “nowhere” attempts at // dereferencing will cause a predictable error.
C+ Dangling Pointers • free(p); // terminate allocation of memory // pointed to by p • The program no longer owns the memory pointed to by p but p still points to that memory • p is now a dangling pointer • If p is dereferenced ( *p ) results are not predictable • Avoid dangling pointers • Assign pointer to NULL after delete:free(p); // p still points to the previously allocated memoryp = NULL; // p now points “nowhere” attempts at // dereferencing will cause a predictable error.
C Dangling Pointers • free(p); // terminate allocation of memory // pointed to by p • The program no longer owns the memory pointed to by p but p still points to that memory • p is now a dangling pointer • If p is dereferenced ( *p ) results are not predictable • Avoid dangling pointers • Assign pointer to NULL after delete:free(p); // p still points to the previously allocated memoryp = NULL; // p now points “nowhere” attempts at // dereferencing will cause a predictable error.