Lecture15 Dynamic Memory Allocation
Lecture15 Dynamic Memory Allocation
An array is a collection of a fixed number of values. Once the size of an array is declared, you can’t
change the size of array.
As it can be seen that the size of above array is 9 but you can’t change the size once the size of an array
is declared.
To solve this problem, we can allocate memory manually during run-time so that we can reallocate the
size of the array which is known as dynamic memory allocation in C programming.
To allocate memory dynamically following library functions are used in C programming and these library
functions are defined in the <stdlib.h> header file.
i. malloc()
ii. calloc()
iii. realloc()
iv. free()
C malloc() method
“malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of
memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any
form.
Syntax:
For Example:
int *ptr;
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds
the address of the first byte in the allocated memory. If space is insufficient, allocation fails and returns a
NULL pointer.
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
return 0;
}
C calloc() method
“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of
blocks of memory of the specified type. It initializes each block with a default value ‘0’.
Syntax:
For Example:
int *ptr;
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of the float. If
space is insufficient, allocation fails and returns a NULL pointer.
0 0 0 0 0
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;
return 0;
}
C free() method
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions
malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the
dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.
Syntax:
free(ptr);
0 0 0 0 0
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
return 0;
}
C realloc() method
where ptr is reallocated with new size ‘newSize’. If space is insufficient, allocation fails and returns a
NULL pointer.
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
free(ptr);
}
return 0;
}
[source: www.geeksforgeeks.org]