DYNAMIC MEMORY ALLOCATION Disadvantages of ARRAYS MEMORY ALLOCATION
- Slides: 30
DYNAMIC MEMORY ALLOCATION
Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements declared is 30 for an array, say int test[30], but the user manipulates with only 10 elements, then the space for 20 elements is wasted. DIFFERENT DATA TYPES COULD NOT BE STORED IN AN ARRAY
§ The use of pointer variable instead of arrays, helps in allocation of memory at RUN TIME, thus memory can be allocated or freed anywhere, anytime during the program execution. • This is known as DYNAMIC MEMORY ALLOCATION
STATIC vs DYNAMIC • The allocation of memory for the specific fixed purposes of a program in a predetermined fashion controlled by the compiler is said to be static memory allocation. • The allocation of memory (and possibly it’s later de allocation) during the run time of a program and under the control of the program is said to be dynamic memory allocation.
Memory Allocation Functions The following are four memory management functions defined in library of C that can be used for allocation and freeing of memory when ever required. » malloc() » calloc() » free() » realloc() include library file <stdlib. h> or <alloc. h> for these functions
malloc ( ) § malloc() : It is a predefined library function that allocates requested size of bytes and returns a pointer to the first byte of the allocated space. § Pointer returned is of type void that has to be type cast to the type of memory block created (int, char, float, double). § Memory allocated with malloc(), could have some garbage value. § General syntax: ptr = (data-type * ) malloc( byte-size ) ; where ptr is pointer of any data type. malloc() returns a pointer to an area of memory with size byte-size.
Alternative int * ptr ; printf ( “n Enter the number of elements in the array “); scanf(“%d”, &n); ptr = ( int *) malloc ( n x sizeof ( int ) ) ; int * ptr ; ptr = ( int *) malloc ( 3*2 ) ;
Example 1 § int *ptr; ptr = (int *) malloc ( 100 * (sizeof (int ) ) ; Returns the size of integer Type cast Number of elements in the array ptr is pointing to. Allocate 200 bytes i. e declare an array of 100 integers with pointer ptr pointing to the first element of the array.
Exercise § Write a program to create an array of integers. Size of the array that is number of elements in the array will be specified interactively by the user at RUN TIME.
#include<stdio. h> #include<stdlib. h> main() { int *ptr; int n, i; printf("Enter number of elements in array"); scanf("%d", &n); ptr=(int*)malloc(n*sizeof(n)); if(ptr==NULL) printf("MEMORY NOT ALLOCATED"); else { printf("MEMORY ALLOCATION SUCCESSFUL"); int *arr; printf("enter elements in array"); for(arr=ptr; arr<ptr+n; arr++) { scanf("%d", arr); } for(arr=ptr; arr<ptr+n; arr++) { printf("%d", *arr); } } free(ptr); }
Example 2 char * cptr ; cptr = ( char * ) malloc ( 10 ) ; This will allocate 10 bytes of memory space for the pointer cptr of type char. cptr pointer holding the address of the first byte of the array of 10 elements ? ? ? 10 bytes of space ? ?
Allocating memory for a struct You can also allocate memory for a struct. Example: struct node *new. Ptr; new. Ptr = (struct node *)malloc(sizeof(struct node)); Memory allocated with malloc() lasts as long as you want it to.
Important § The storage space allocated dynamically has NO name and therefore its contents are accessed ONLY through a pointer. § malloc() allocates blocks of contiguous memory locations. § If allocation fails due to in sufficient space, it returns NULL pointer. Thus when ever we allocate memory it should be checked whether the memory has assigned successfully or not.
Visualization If size = 10 => 20 bytes will be allocated. Integer pointer * table pointing to first element of array
SOLUTION cont’d: Reading values in the array // reading values in array printf(“n Input table value “); for( p= table; p<table + size ; p++) scanf(“%d”, p ); // no ampersand as p is pointer // printing values of array in reverse order for( p = table+size – 1 ; p >= table ; p-- ) printf(“%d”, *p);
Visualization table for( p= table; p<table + size ; p++) scanf(“%d”, p ); pointer * p
Printing values in reverse order for( p = table+size – 1 ; p >= table ; p-- ) * table printf(“ %d stored at address %u”, *p, p); pointer * p
OUTPUT What is the size of array ? 5 Address of first byte : 2262 Input values: 11 12 13 14 15 OUTPUT values in reverse order 15 stored at address 2270 14 stored at address 2268 13 stored at address 2266 12 stored at address 2264 11 stored at address 2262
calloc() § while malloc() allocates single block of storage, calloc() allocates multiple block of storage, each of the same size and then sets all bytes to 0 § calloc() is a memory allocation function normally used for requesting memory space at run time for storing derived data types like arrays and structures
calloc ( ) § calloc ( ): It also allocates the requested number of bytes, but the difference is that it takes two parameters: » N : number of elements » Element_size: size of element in bytes § Also when the memory is allocated, all the elements are assigned a initial value of zero. § This is not provided by function malloc ( ) General syntax: ptr = (cast _type * ) calloc (n, element_size);
§ The above statement allocates contiguous space for n elements, each of size element_size. § All elements are initialized to zero and a pointer to the first byte of the allocated region is returned. § If there is not enough space, a NULL pointer is returned.
struct student { char name[20]; float age; int id; }; typedef struct student record; record * stptr; int size = 30; stptr = (record *)calloc(size, sizeof(record)); if(stptr == NULL) { exit(1); }
realloc() If you find you did not allocate enough space use realloc(). You give realloc() a pointer (such as you received from an initial call to malloc()) and a new size, and realloc does what it can to give you a block of memory big enough to hold the new size. int *ip; ip = (int*)malloc(100 * sizeof(int)); . . . /* need twice as much space */ ip = (int*)realloc(ip, 200 * sizeof(int));
§ § § § § #include <stdio. h> #include <stdlib. h> int main() { int *ptr, i , n 1, n 2; printf("Enter size of array: "); scanf("%d", &n 1); ptr = (int*) malloc(n 1 * sizeof(int)); printf("Address of previously allocated memory: "); for(i = 0; i < n 1; ++i) printf("%ut", ptr + i); printf("n. Enter new size of array: "); scanf("%d", &n 2); ptr = realloc(ptr, n 2*sizeof(int)); for(i = 0; i < n 2; ++i) printf("%ut", ptr + i); return 0; }
Releasing the Used Space § In case of Dynamic RUN Time allocation, it is the responsibility of the programmer to release the memory space when it is not required by the program. § When a block of data in memory is no longer needed by the program, it should be released as memory is a factor in executing complex programs.
free ( ) § To release the memory currently allocated to a pointer using DYNAMIC ALLOCATION use the following function: free ( ptr ); where ptr is a pointer to a memory block which has already been created using either malloc() or calloc ().
Creating 2 -d array at run time Method 1 - usingle pointer § § § § § . #include <stdio. h> #include <stdlib. h> int main() { int r = 3, c = 4; int *arr = (int *)malloc(r * c * sizeof(int)); int i, j, count = 0; for (i = 0; i < r; i++) for (j = 0; j < c; j++) *(arr + i*c + j) = ++count; for (i = 0; i < r; i++) for (j = 0; j < c; j++) printf("%d ", *(arr + i*c + j)); /* Code for further processing and free the dynamically allocated memory */ return 0; }
Creating 2 -d array at run time Method 2 - using array of pointers § § § § § #include <stdio. h> #include <stdlib. h> int main() { int r = 3, c = 4, i, j, count; int *arr[r]; for (i=0; i<r; i++) arr[i] = (int *)malloc(c * sizeof(int)); // Note that arr[i][j] is same as *(*(arr+i)+j) count = 0; for (i = 0; i < r; i++) for (j = 0; j < c; j++) arr[i][j] = ++count; // Or *(*(arr+i)+j) = ++count for (i = 0; i < r; i++) for (j = 0; j < c; j++) printf("%d ", arr[i][j]); /* Code for further processing and free the dynamically allocated memory */ return 0; }
Creating 2 -d array at run time Method 3 - using pointer to pointers § § § § § #include <stdio. h> #include <stdlib. h> int main() { int r = 3, c = 4, i, j, count; int **arr = (int **)malloc(r * sizeof(int *)); for (i=0; i<r; i++) arr[i] = (int *)malloc(c * sizeof(int)); // Note that arr[i][j] is same as *(*(arr+i)+j) count = 0; for (i = 0; i < r; i++) for (j = 0; j < c; j++) arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count for (i = 0; i < r; i++) for (j = 0; j < c; j++) printf("%d ", arr[i][j]); /* Code for further processing and free the dynamically allocated memory */ return 0; }
How pointer to pointers method works
- Advantages of dynamic memory allocation
- Example of dynamic memory allocation
- Knuth's boundary tags
- Knuth’s boundary tags
- Example of dynamic memory allocation
- Dynamic data structure
- Dynamic memory allocation in data structure
- Dma dynamic memory allocation
- Dynamic memory allocation c++
- Memory allocation in java
- Calloc example
- Dynamic arrays and amortized analysis
- Are vectors dynamic arrays
- Array advantages and disadvantages
- Linked allocation
- Dynamic strategies for asset allocation
- What is dynamic storage allocation problem in os
- Polymorphism dynamic allocation
- Assumptions for dynamic channel allocation
- Dynamic storage allocation
- Gpon dba
- Buddy memory allocation
- Single user contiguous scheme in operating system
- Demand paged memory allocation
- Memory allocation policy
- Reduce external fragmentation
- Demand paged memory allocation
- What are two goals of multitasking memory allocation
- Non contiguous memory allocation
- Non contiguous memory allocation
- Paging in non contiguous memory allocation