Dynamic Memory allocation
Dynamic Memory allocation
Memory Allocation
Static Dynamic
Memory Allocation Memory Allocation
malloc()
Syntax of malloc()
Example
ptr = (float*) malloc(100 * sizeof(float));
The above statement allocates 400 bytes of memory. It's because the size of float is 4 bytes.
The pointer ptr holds the address of the first byte in the allocated memory.
Example
Ptr=(char*) malloc(6);
#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);
}
return 0;
}
calloc()
➢ The name "calloc" stands for contiguous allocation.
➢ The calloc() function allocates multiple blocks of memory of same size and initializes all bits to
zero.
➢ Generally used in array.
Syntax of calloc()
n=no. of blocks
Example:
-The above statement allocates contiguous space in memory for 25 elements of type float.
malloc() calloc()
malloc() function will create a single block of calloc() function can assign multiple blocks of
memory of size specified by the user. memory for a variable.
It takes one argument, i.e the size of block. It takes two arguments, i.e the no. of blocks and the
size of each block.
malloc() function contains garbage value. The memory block allocated by a calloc()
function is always initialized to zero.
malloc is faster than calloc. calloc takes little longer than malloc because of the
extra step of initializing the allocated memory by
zero. However, in practice the difference in speed is
very tiny and not recognizable.
free()
Syntax of free()
free(ptr);
-ptr is a pointer to a memory block ,which has already been created by malloc or calloc.
-To release an array of elements, only need to release the pointer once. It is an error to attempt to release
elements individually.
5
realloc()
➢ If the dynamically allocated memory is insufficient or more than required, you can alter the size
of previously allocated memory using the realloc() function.
Syntax of realloc()
Here, ptr is reallocated with a new size x and points to the first byte of the new memory block.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
free(ptr);
return 0;
}
Output:
Enter size: 2
Addresses of previously allocated memory:26855472
26855476
6
Questions:
1. What is meant by dynamic memory allocation? Differentiate between malloc and calloc.
2. Write a program to input and print text using Dynamic Memory Allocation.
3. Write a program to read and print the student details using structure and Dynamic Memory Allocation.