Dynamic memory allocation

19
Dynamic memory allocation

description

Dynamic memory allocation

Transcript of Dynamic memory allocation

Page 1: Dynamic memory allocation

Dynamic memory allocation

Page 2: Dynamic memory allocation

Dynamic memory allocation• Process of allocating memory at run time is

known as dynamic memory allocation• Memory allocation functions:-

– malloc :- allocates required size of bytes and returns a pointer to the first byte of allocated space

– calloc:- allocates space for an array elements, initialises them and returns a pointer to the first byte of allocated space

– free :- frees previously allocated space– realloc:- modifies the size of previously allocated

space

Page 3: Dynamic memory allocation

mallocmalloc function allocates a single block of memory of specified number of bytes at run time returning a void pointer type. Hence we can assign it to any datatype.

General formPtr = (cast-type *) malloc(byte-size)

ExampleX = (int *) malloc(100 * sizeof(int)); /*allocates 100 * 2 bytes of memory space the start address assigned to pointer variable x */cptr = (char*) malloc(10); // allocates 10 bytes of space

st_var = (struct store*) malloc(10 * sizeof(struct store)); /* allocates space for 10 structures of type store */

Dynamically allocated space has no predefined name and hence its contents can be accessed only through its pointer

Page 4: Dynamic memory allocation

A program using malloc/* an example program to illustrate use of variable length of array by using dynamic memory allocation function “malloc”*/#include <stdlib.h>#include <stdio.h>#define NULL 0void main(){int *arrptr,*arrptr1, num,i; // declare array pointer variable arptrclrscr();printf("Enter the number of elements to be stored\n”);scanf("%d",&num);arrptr = (int*)malloc( num * sizeof(int));

if(arrptr == NULL){printf("sorry no space available in memory\n");exit(1);}arrptr1=arrptr;for( i=0;i<num;i++) { // enter numbers into array of integerprintf("\n Enter number[%d] ",i);scanf( "%d",arrptr+i);}for( i=0;i<num;i++) // print numbers from array of integerprintf( "\n number[%d] is %d",i,*(arrptr1+i));

getch();}

Page 5: Dynamic memory allocation

A program using malloc/* an example program to illustrate sum of variable length of arrays by using dynamic

memory allocation function “malloc”*/

#include <stdlib.h>

#include <stdio.h>

void main(){

int *arr1,*arr2,num,*sum,i; // declare array pointer variable arptr

Printf("Enter the number of elements to be stored\n", num);

scanf("%d",&num);

arr1 = (int*)malloc( num * sizeof(int));

arr2 = (int*)malloc( num * sizeof(int));

sum = (int*)malloc( num * sizeof(int));

printf("\n Enter values in 1st array”);

for( i=0;i<num;i++) // enter numbers into array of integer

scanf( "%d",arr1+i);

printf("\n Enter values in 2nd array");

for( i=0;i<num;i++) // enter numbers into array of integer

scanf( "%d",arr2+i);

Printf(“\n the sum of two arrays:\n”);

for( i=0;i<num;i++) // sum and print numbers from array of integer

{ *(sum+i)=*(arr1+i) + *(arr2+i);

printf( “%d“,*(sum+i));

}

}

Page 6: Dynamic memory allocation

calloccalloc function allocates a contiguous multiple blocks of memory of same size at run time. Useful for storing derived data types such as arrays and structure.All bytes are initialised to zero.

General formptr = (cast-type *) calloc(n, elem-size); // space for n blocks of size elem-size

ExampleX = (record *) calloc(n, sizeof(record)); /*allocates n memory spaces of type record. the start address assigned to pointer variable x */

Dynamically allocated space has no predefined name and hence its contents can be accessed only through its pointer

Page 7: Dynamic memory allocation

A program using calloc/* an example program to illustrate use of variable length of array by using dynamic memory allocation function "calloc"*/#include <stdlib.h>#include <stdio.h>#define NULL 0void main(){char name[20], *arrptr,*arrptr1;// declare array pointer variable arptrint num,i;clrscr();printf("Enter the number of elements to be stored\n", &num);scanf("%d",&num);arrptr = (char *)calloc( num, sizeof(name));if(arrptr == NULL){printf("sorry no space available in memory\n");exit(1);}arrptr1=arrptr;for( i=0;i<num;i++) { // enter names into array of charsprintf("\n Enter name[%d] ",i);scanf( "%s",arrptr+(i*sizeof(name)));}for( i=0;i<num;i++) // print names from array of charsprintf( "\n name[%d] is %s ",i,arrptr1+(i*sizeof(name)));getch();}

Page 8: Dynamic memory allocation

free and reallocfreeCompile time storage is allocated and de-allocated by the system in accordance with its storage class.

Dynamic allocation is done by the user after compilation at run time and hence it is the user’s responsibility to release the space when it is no more required.

The function to release memory is : free(ptr); // ptr is the start of memory block returned by malloc or calloc

realloc

When the allocation by malloc or calloc requires to be increased or decreased then the modification can be done by function realloc:-ptr = realloc(ptr, newsize); // ptr is the original ptr returned by malloc for e.g.A=(char*) realloc(A,50);

Page 9: Dynamic memory allocation

Dynamic allocation of matrix/* program to dynamically create 2 dim arrays and Transposes the array */

#include <stdio.h>#include <stdlib.h>#include <conio.h>

void main(){ int i,j,nrows,ncols;

// declaring base pointer to pointer for arrays int** arrayA; int** arrayB; clrscr();// Define the size of the array at run time printf("Enter number of rows\n"); scanf("%d",&nrows); printf("Enter number of columns\n"); scanf("%d",&ncols);

Page 10: Dynamic memory allocation

Dynamic allocation of matrix ( contd..)

// -------arrayA---------------// allocation of rows to arrayA arrayA=(int**)malloc(nrows*sizeof(int*));

// allocation of columns to arrayA for (i=0; i<nrows; i++) arrayA[i]=(int*)malloc(ncols*sizeof(int));

// ------arrayB-----------------// allocation of rows to arrayB arrayB=(int**)malloc(nrows*sizeof(int*));

// allocation of columns to arrayB for (i=0; i<nrows; i++) arrayB[i]=(int*)malloc(ncols*sizeof(int));

Page 11: Dynamic memory allocation

Dynamic allocation of matrix ( contd..)//Enter data into arrayA for (i=0; i<nrows; i++) {

printf("\n Enter data for next row");for (j=0; j<ncols; j++){ printf("\n enter data next column "); scanf("%d",&arrayA[i][j]);}

}

// Transpose arrayA data into arrayBfor (i=0; i<nrows; i++) {

for (j=0; j<ncols; j++){ arrayB[i][j] = arrayA[j][i]; }

}

Page 12: Dynamic memory allocation

Dynamic allocation of matrix ( contd..)// printing arrayAprintf("\n\n-------Array A------\n\n");for (i=0; i<nrows; i++) {

printf("\n\n");for (j=0; j<ncols; j++){ printf("%5d",arrayA[i][j]);}

}

// printing arrayBprintf("\n\n---Transposed Array A---\n\n");for (i=0; i<nrows; i++) {

printf("\n\n");for (j=0; j<ncols; j++){ printf("%5d",arrayB[i][j]);}

}

Page 13: Dynamic memory allocation

Dynamic allocation of matrix ( contd..)printf("\n\n");getch();// free allocated spacesfor (i=0; i<nrows; i++) { free((void*)arrayA[i]); free((void*)arrayA); free((void*)arrayB[i]); free((void*)arrayB); }}

Page 14: Dynamic memory allocation

Multiplication of Arrays/* program to dynamically create 2 dim arrays and Multiplies them into a third one*/#include <stdio.h>#include <stdlib.h>#include <conio.h>void main(){ int i,j,k,nrows,ncols;

// declaring base pointer to pointer for arrays int** arrayA; int** arrayB; int** arrayC; clrscr();// Define the size of the array at run time printf("Enter number of rows\n"); scanf("%d",&nrows); printf("Enter number of columns\n"); scanf("%d",&ncols);

Page 15: Dynamic memory allocation

Multiplication of Arrays ( contd..)

// -------arrayA---------------// allocation of rows to arrayA arrayA=(int**)malloc(nrows*sizeof(int*));

// allocation of columns to arrayA for (i=0; i<nrows; i++) arrayA[i]=(int*)malloc(ncols*sizeof(int));

// ------arrayB-----------------// allocation of rows to arrayB arrayB=(int**)malloc(nrows*sizeof(int*));

// allocation of columns to arrayB for (i=0; i<nrows; i++) arrayB[i]=(int*)malloc(ncols*sizeof(int));

Page 16: Dynamic memory allocation

Multiplication of Arrays ( contd..)// ------arrayC-----------------// allocation of rows to arrayC arrayC=(int**)malloc(nrows*sizeof(int*));

// allocation of columns to arrayC for (i=0; i<nrows; i++) arrayC[i]=(int*)malloc(ncols*sizeof(int));

//Enter data into arrayA for (i=0; i<nrows; i++) {

printf("\n Enter data for next row");for (j=0; j<ncols; j++){ printf("\n enter data next column "); scanf("%d",&arrayA[i][j]);}

}

Page 17: Dynamic memory allocation

Multiplication of Arrays ( contd..)// Transpose arrayA data into arrayBfor (i=0; i<nrows; i++) {

for (j=0; j<ncols; j++){ arrayB[i][j] = arrayA[j][i]; }

}

// Multiply arrayA with arrayB and store result data into arrayCfor (i=0; i<nrows; i++) {

for (j=0; j<ncols; j++){ arrayC[i][j] =0;

for (k=0; k<ncols; k++) arrayC[i][j] += arrayA[i][k] * arrayB[k][j]; }

}

Page 18: Dynamic memory allocation

Multiplication of Arrays ( contd..)/ printing arrayAprintf("\n\n-------Array A------\n\n");for (i=0; i<nrows; i++) {

printf("\n\n");for (j=0; j<ncols; j++){ printf("%5d",arrayA[i][j]);}

}

// printing arrayBprintf("\n\n------Array B------\n\n");for (i=0; i<nrows; i++) {

printf("\n\n");for (j=0; j<ncols; j++){ printf("%5d",arrayB[i][j]);}

}

Page 19: Dynamic memory allocation

Multiplication of Arrays ( contd..)// printing arrayCprintf("\n\n-----Result of Multiplication: Array C------\n\n");for (i=0; i<nrows; i++) {

printf("\n\n");for (j=0; j<ncols; j++){ printf("%5d",arrayC[i][j]);}

}printf("\n\n");getch();// free allocated spacesfor (i=0; i<nrows; i++) { free((void*)arrayA[i]); free((void*)arrayA); free((void*)arrayB[i]); free((void*)arrayB); free((void*)arrayC[i]); free((void*)arrayC); }}