Dynamic memory allocation
Dynamic memory allocation
functions
• Malloc()
• Calloc()
• Realloc()
• Free()
Malloc()
• The “malloc” or “memory
allocation” method in C is used to
dynamically allocate a single large block of
memory with the specified size.
• Syntax- ptr = (datatype*)malloc(byte-size)
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n"); exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Calloc()
• calloc” or “contiguous allocation” method
in C is used to dynamically allocate the
specified number of blocks of memory of
the specified type.
• It is very much similar to malloc()
• It initializes each block with a default
value ‘0’.
Syntax
• ptr = (cast-type*)calloc(n, element-size);
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by calloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Difference between malloc() and calloc()
Malloc() Calloc()
• malloc() is a function • calloc() is a function that
that creates one block of assigns a specified number
memory of a fixed size. of blocks of memory to a
• malloc() only takes one single variable.
argument. • calloc() takes two
arguments.
• malloc() is used to
• calloc() is used to indicate
indicate memory contiguous memory
allocation. allocation.
• malloc() does not • calloc() initializes the
initialize the memory to memory to zero.
zero.