Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Programming

Similar presentations


Presentation on theme: "Introduction to Programming"— Presentation transcript:

1 Introduction to Programming
Lecture 24

2 Today’s Agenda Memory Allocation Dynamic memory allocation
Advantages/disadvantages of Dynamic and static memory allocation Common programming errors while using Dynamic memory allocation

3 Static Memory Allocation
int i , j , k ; char s [ 20 ] ;

4 Compile Time Allocation

5 Dynamic Memory Allocation

6 Heap

7 Pointers

8 void Pointer

9 int *i ; char *s ; i is a pointer to an integer

10 void *ptr ;

11 Cast

12 void *ptr ;

13 ( int * ) ptr ;

14 NULL

15 calloc ( n , m ) ; Space in terms of numbers of elements
Space in terms of size each of elements

16 calloc ( 1000 , sizeof ( int ) ) ;

17 ( int * ) calloc ( 1000 , sizeof ( int ) ) ;

18 void * calloc ( size_t n , size_t el-size ) ;

19 Example 1 int *iPtr ; iPtr = ( int * ) calloc ( 1000 , sizeof ( int ) ) ; if ( iPtr == NULL ) exit ( ) ;

20 Number of bytes required
void * malloc ( n ) ; Number of bytes required

21 malloc (1000 *sizeof ( int ) ) ) ;

22 malloc ( n ( sizeof ( float ) ) ) ;

23 Static Memory Allocation
#define MAXSTUDENT 100 int Student [ MAXSTUDENT ] ;

24 Problem statement Find the average age of the students in your class

25 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++ ;

26 free ( iPtr ) ;

27 realloc(void *iPtr, size_t size);

28 Unreferenced Memory

29 Memory Leaks

30 Example main ( ) { funct ( ) ; } funct ( ) int *iPtr ;
iPtr = malloc ( * ( sizeof ( int ) ) ) ; // used the memory

31 Dangling Pointers

32 Example int *ptr1 , *ptr2 ; ptr1 = malloc (1000 * ( sizeof ( int ) ) ) ; ptr2 = ptr1 ; - - - free ( ptr1 ) ;

33 Multi-tasking

34 Review Dynamic Memory Allocation Efficient usage of computers
resources Have to do memory management


Download ppt "Introduction to Programming"

Similar presentations


Ads by Google