Dynamic Memory Allocation in C
Dynamic Memory Allocation in C
Function Description
malloc() allocates requested size of bytes and returns a void pointer pointing to the first byte
of the allocated space
calloc() allocates space for an array of elements, initialize them to zero and then returns a
void pointer to the memory
calloc() is another memory allocation function that is used for allocating memory at
runtime. calloc function is normally used for allocating memory to derived data types
such as arrays and structures. If it fails to allocate enough space as specified, it returns
a NULL pointer.
Syntax:
void *calloc(number of items, element-size)
Time for an Example: calloc()
struct employee
{
char *name;
int salary;
};
typedef struct employee emp;
emp *e1;
e1 = (emp*)calloc(30,sizeof(emp));
Syntax:
void* realloc(pointer, new-size)
Diffrence between malloc() and calloc()
calloc() malloc()
calloc() initializes the allocated memory malloc() initializes the allocated memory with
with 0 value. garbage values.
Syntax : Syntax :
(cast_type *)calloc(blocks , size_of_block); (cast_type *)malloc(Size_in_bytes);
Program to represent Dynamic Memory
Allocation(using calloc())
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n;
int *element;
/*
returns a void pointer(which is type-casted to int*)
pointing to the first block of the allocated space
*/
element = (int*) calloc(n,sizeof(int));
/*
If it fails to allocate enough space as specified,
it returns a NULL pointer.
*/
if(element == NULL)
{
printf("Error.Not enough space available");
exit(0);
}
return 0;
}
4 2 1 5 3
Smallest element is 1