2. Dynamic Memory Allocation
• The process of allocating memory during run
time(Execution time) is known dynamic
memory allocation.
• The memory for dynamically allocated
variables are allocated on the heap.
3. • Ability of a program to use more memory
space at execution time
• Memory space required can be specified at
the time of execution.
• C supports allocating and freeing memory
dynamically using library routines.
• These functions are available in stdlib.h
4. Memory Allocation Functions
• malloc – Allocates requested number of bytes
and returns a pointer to the first byte of the
allocated space.
• calloc – Allocates space for an array of
elements, initializes them to zero and then
returns a pointer to the memory.
• Free- Frees previously allocated space.
• realloc – Modifies the size of previously
allocated space.
5. malloc()
• The name "malloc" stands for memory
allocation.
• The malloc() function reserves a block of
memory of the specified number of bytes.
• It returns a pointer of void which can be
casted into pointers of any form.
Syntax of malloc()
• voidptr = (castType*) malloc(size);
6. Examples
• int *p;
• p = (int *) malloc (100 * sizeof (int)) ;
• A memory space equivalent to “100 times the
size of an int” bytes is reserved.
• The address of the first byte of the allocated
memory is assigned to the pointer p of type
int.
P
7. Example
• float *ptr;
• ptr = (float*) malloc(100 * sizeof(float));
• The above statement allocates 800 bytes of
memory. It's because the size of float is 8
bytes.
• And, the pointer ptr holds the address of the
first byte in the allocated memory.
8. Write statements
• Allocate memory of storing 50 integers
• Allocate memory of storing 40 characters
• Allocate memory of storing 120 double values
• Allocate memory of storing 150 floating point
values
9. Answers
• Allocate memory of storing 50 integers
iVar=(int*)malloc(50*sizeof(int));
• Allocate memory of storing 40 characters
cVar=(char*)malloc(40*sizeof(char));
• Allocate memory of storing 120 double values
dVar=(double*)malloc(120*sizeof(double));
• Allocate memory of storing ‘n’ floating point values
fVar=(float*)malloc(n*sizeof(float));
11. C program to create memory for int,
char and float variable at run time.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *iVar;
char *cVar;
float *fVar;
/*allocating memory dynamically*/
iVar=(int*)malloc(1*sizeof(int));
cVar=(char*)malloc(1*sizeof(char));
fVar=(float*)malloc(1*sizeof(float));
printf("Enter integer value: ");
scanf("%d",iVar);
printf("Enter character value: ");
scanf(" %c",cVar);
printf("Enter float value: ");
scanf("%f",fVar);
printf("Inputted value are: %d, %c,
%.2fn",*iVar,*cVar,*fVar);
/*free allocated memory*/
free(iVar);
free(cVar);
free(fVar);
return 0;
}
12. • voidptr = (castType*) malloc(size);
• Void pointer- any type accepted
• Return value is a pointer to the beginning of
the block of memory allocated.
• It returns NULL pointer if it could not able to
allocate requested amount of memory.
• It does not initialize the memory allocated
during execution. It carries garbage value.
13. C program to input and print text
using Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
char *text;
printf("Enter limit of the text: ");
scanf("%d",&n);
/*allocate memory dynamically*/
text=(char*)malloc(n*sizeof(char));
printf("Enter text: ");
gets(text);
printf("Inputted text is: %sn",text);
/*Free Memory*/
free(text);
return 0;
}
Output:
Enter limit of the text: 100
Enter text: Welcome to C
Programming.
Inputted text is: Welcome to C
Programming.
14. Program to calculate the sum of n
numbers entered by the user
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements:
");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(ptr == NULL)
{
printf("Error! memory not
allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
15. C program to read and print the student details
using structure and Dynamic Memory
Allocation.
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name[30];
int roll;
float perc;
};
int main()
{
struct student *pstd;
/*Allocate memory dynamically*/
pstd=(struct student*)malloc(1*sizeof(struct student));
16. if(pstd==NULL)
{
printf("Insufficient Memory,
Exiting... n");
return 0;
}
/*read and print details*/
printf("Enter name: ");
gets(pstd->name);
printf("Enter roll number: ");
scanf("%d",&pstd->roll);
printf("Enter percentage: ");
scanf("%f",&pstd->perc);
printf("nEntered details
are:n");
printf("Name: %s, Roll
Number: %d, Percentage:
%.2fn",pstd->name,pstd-
>roll,pstd->perc)
return 0;
}
Output:
Enter name: Mike
Enter roll number: 1
Enter percentage: 87.50
Entered details are:
Name: Mike, Roll Number: 1,
Percentage: 87.50
17. C program to read and print the N student
details using structure and Dynamic Memory
Allocation
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name[30];
int roll;
float perc;
};
int main()
{
struct student *pstd;
int n,i;
printf("Enter total number of
elements: ");
scanf("%d",&n);
/*Allocate memory dynamically for n
objetcs*/
pstd=(struct
student*)malloc(n*sizeof(struct
student));
if(pstd==NULL)
{
printf("Insufficient Memory,
Exiting... n");
return 0;
}
19. calloc()
• The name "calloc" stands for contiguous allocation.
• calloc() allocates multiple blocks of memory each of
same size and sets all bytes to zero.
• calloc() takes two arguments:
– the number of blocks to be allocated
– the size of each block (in bytes)
• calloc() returns the address of the chunk of memory
that was allocated
• calloc() also sets all the values in the allocated memory
to zeros
• calloc()is also used to dynamically allocate arrays
20. Syntax and Example
Syntax:
ptr = (castType*)calloc(n, size);
Example 1:
• ptr = (float*) calloc(25, sizeof(float));
• The above statement allocates contiguous space in memory
for 25 elements of type float.
Example2:
For instance, to dynamically allocate an array of 10 ints:
• int*arr;
• arr= (int*) calloc(10, sizeof(int));
• /* now arrhas the address
• of an array of 10 ints, all 0s */
21. Difference between malloc() and
calloc()
• malloc() allocates single block of memory
whereas leaves the memory uninitialized.
• calloc() function allocates multiple blocks of
memory of same size and initializes all bits to
zero.
22. free()
• Dynamically allocated memory created with
either calloc() or malloc() doesn't get freed on
their own.
• You must explicitly use free() to release the
space.
Syntax of free()
free(ptr);
• This statement frees the space allocated in the
memory pointed by ptr.
23. Program to calculate the sum of n numbers
entered by the user using calloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements:
");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not
allocated.");
exit(0); }
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
24. Realloc
• It is used to dynamically change the memory
allocation of a previously allocated memory.
• If the memory previously allocated with the help of
malloc or calloc is insufficient, realloc can be used
to dynamically re-allocate memory.
Syntax:
• ptr= realloc(ptr, num_bytes);
• where ptr is reallocated with new size 'newSize'.
–Find space for new allocation
–Copy original data into new space
–Free old space
–Return pointer to new space
25.
26. Dynamically Allocating 2D Array
float **A; /* A is an array (pointer) of float pointers */
int I;
A = (float **) calloc(5,sizeof(float *));
/* A is a 1D array (size 5) of float pointers */
for (I = 0; I < 5; I++)
A[I] = (float *) calloc(4,sizeof(float));
/* Each element of array points to an array of 4 float variables */
/* A[I][J] is the Jth entry in the array that the Ithmember of A
points to */