Dynamic Memory
Allocation in C
The process of allocating memory at runtime is known as dynamic
memory allocation. Library routines known as memory management
functions are used for allocating and freeing memory during execution
of a program. These functions are defined in stdlib.h header
file.
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
|
free
|
releases previously allocated memory
|
realloc
|
modify the size of previously allocated space
|
C malloc()
The name malloc stands for "memory allocation".
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.ptr = (int*) malloc(100 * sizeof(int));
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:
ptr = (float*) calloc(25, sizeof(float));
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.
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed
by
ptr
.
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);
Here, ptr is
reallocated with size of newsize.