90 likes | 108 Views
Lecture 13. Static vs Dynamic Memory Allocation malloc(), calloc(), free() Reading Assignments: Chapter 9, Section 9. Memory. a[0]. a[1]. a[2]. Static Memory Allocation. If the size of array is known before compilation, we do. int a[3];.
E N D
Lecture 13 • Static vs Dynamic Memory Allocation • malloc(), calloc(), free() • Reading Assignments: • Chapter 9, Section 9
Memory a[0] a[1] a[2] Static Memory Allocation • If the size of array is known before compilation, we do int a[3]; • How about if the number of elements we want is unknown?
Memory a /* memory allocation */ a = (int *) malloc (numbers*sizeof(int)); Dynamic Memory Allocation int *a = NULL; int numbers; printf(“How many elements you want?\n”); scanf( “%d”, &numbers); a
Dynamic Memory Allocation malloc calloc
Dynamic memory allocation • In order to acquire storage during program execution, C provides calloc() and malloc() (available in stdlib.h) for dynamic memory allocation • To allocate a contiguous memory space for n object of a type, use calloc(n, object_size) • calloc()returns a pointer to the starting address of the allocated memory if enough memory can be found; otherwise, a NULL value is returned; the storage gained is initialized to zero
Dynamic memory allocation (cont’) • malloc()returns a pointer to the starting address of the allocated memory if enough memory can be found; otherwise, a NULL value is returned; its format is malloc(object_size) • The function prototypes of calloc() and malloc()are void *malloc(size_t) void *calloc(int, size_t) • The storage set aside by malloc()is NOT initialized
Dynamic memory allocation (cont’) • As the pointers returned by malloc()and malloc()is of type void*, they can be assigned to other pointers without casting • Space allocated by calloc() and malloc() is not released on function exit (but it is released on program exit) and has to be released by calling a system library function free() (available in stdlib.h) • The prototype for free() is void free(void *ptr);
Dynamic memory allocation (cont’) • Since the size of a data object of a particular data type is machine-dependent, sizeof() is often used when malloc()or calloc()is called, e.g., int *a; … /* get memory space for 5 integers */ if ((a = (int *) calloc(5, sizeof(int)))==NULL) { printf(“calloc() failed\n”); exit(1); } ... free(a); /* free the space */ ...
Dynamic Memory Allocation int *a = NULL; int i, numbers; printf(“How many elements you want?\n”); scanf( “%d”, &numbers); /* allocate memory space */ if ((a=(int *) malloc(numbers*sizeof(int))) == NULL){ printf(“Not Enough Memory Space!\n”); exit(-1); /* end the program */ } for (i = 0; i < numbers; i++) a[i] = i*i; /* free memory space */ free(a);