C Dynamic Memory Allocation:
Sometimes the size of an array which we declared may be insufficient in storage. To resolve this issue, we can allocate memories manually during run-time. This process is known as dynamic memory allocation in C programming.
To allocate the memory dynamically in C, library functions used are malloc(), calloc(), realloc() and free() are used. These functions are defined in the <stdlib.h> header file.
C malloc()
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a pointer of void which can be casted into pointers of any form.
Syntax:
ptr = (castType*) malloc(size); C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their own. You must explicitly use free() to release the space.
Syntax:
free(ptr);
C calloc()
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory uninitialized. Whereas, the calloc() function allocates memory and initializes all bits to zero.
Syntax:
ptr = (castType*)calloc(n, size); C realloc()
If the dynamically allocated memory is insufficient or more than
required, you can change the size of previously allocated memory using
the realloc() function.
Syntax:
ptr = realloc(ptr, x);
Example:



Comments
Post a Comment
if you have any doubts, pls let me know