Dynamic Memory Allocation ARCC
Dynamic Memory Allocation ARCC
C malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of specified size and return a pointer of type void which
can be casted into pointer of any form.
Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of
byte size. If the space is insufficient, allocation fails and returns NULL pointer.
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer
points to the address of first byte of memory.
C calloc()
The name calloc stands for "contiguous allocation".
The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas
calloc() allocates multiple blocks of memory each of same size and sets all bytes to Zero.
Syntax of calloc()
ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4
bytes.
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own. You must
explicitly use free() to release the space.
Pravat Sinha,Call &WhatsApp: 9091454548
Asansol Rainbow Computer Centre
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
Write a C program to find sum of n elements entered by user. To perform this program, allocate
memory dynamically using malloc() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
Write a C program to find sum of n elements entered by user. To perform this program, allocate
memory dynamically using calloc() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
C realloc()
If the previously allocated memory is insufficient or more than required, you can change the previously
allocated memory size using realloc().
Syntax of realloc()
ptr = realloc(ptr, newsize);
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);