Introduction to Programming Lecture 24
Today’s Agenda Memory Allocation Dynamic memory allocation Advantages/disadvantages of Dynamic and static memory allocation Common programming errors while using Dynamic memory allocation
Static Memory Allocation int i , j , k ; char s [ 20 ] ;
Compile Time Allocation
Dynamic Memory Allocation
Heap
Pointers
void Pointer
int *i ; char *s ; i is a pointer to an integer
void *ptr ;
Cast
void *ptr ;
( int * ) ptr ;
NULL
calloc ( n , m ) ; Space in terms of numbers of elements Space in terms of size each of elements
calloc ( 1000 , sizeof ( int ) ) ;
( int * ) calloc ( 1000 , sizeof ( int ) ) ;
void * calloc ( size_t n , size_t el-size ) ;
Example 1 int *iPtr ; iPtr = ( int * ) calloc ( 1000 , sizeof ( int ) ) ; if ( iPtr == NULL ) exit ( ) ;
Number of bytes required void * malloc ( n ) ; Number of bytes required
malloc (1000 *sizeof ( int ) ) ) ;
malloc ( n ( sizeof ( float ) ) ) ;
Static Memory Allocation #define MAXSTUDENT 100 int Student [ MAXSTUDENT ] ;
Problem statement Find the average age of the students in your class
Example 2 int numstd ; int *iPtr , *sPtr ; cout << "Enter the number of students " << endl ; cin >> numstd ; iPtr = malloc ( numstd * ( sizeof ( int ) ) ) ; if ( iPtr == NULL ) { cout << "Error on malloc " ; return 1 ; /* Use a nonzero return to indicate an error has occurred */ } // a while loop to read the ages of the student and place them in the memory sPtr = iPtr ; sPtr++ ;
free ( iPtr ) ;
realloc(void *iPtr, size_t size);
Unreferenced Memory
Memory Leaks
Example main ( ) { funct ( ) ; } funct ( ) int *iPtr ; iPtr = malloc ( 1000 * ( sizeof ( int ) ) ) ; // used the memory
Dangling Pointers
Example int *ptr1 , *ptr2 ; ptr1 = malloc (1000 * ( sizeof ( int ) ) ) ; ptr2 = ptr1 ; - - - free ( ptr1 ) ;
Multi-tasking
Review Dynamic Memory Allocation Efficient usage of computers resources Have to do memory management