C Dynamic Memory Allocation
The dynamic memory allocation is the process of allocating memory at runtime.
There are four dynamic memory allocation functions:-
- malloc( )
- calloc( )
- realloc( )
- free( )

malloc( ):
The malloc( ) function is used to allocate a block of memory and it returns the void pointer to the address of the first byte in the memory. Declaration of malloc( ) is:
Void * malloc( size_t size);
Here size_t represents the type that is usually an unsigned integer. It is defined in several header files including stdio.h. The size of malloc’s actual parameters is defined by using the sizeof operator.
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main() {
char name[100];
char *scope;
strcpy( name, "Welcome To Onlinetpoint");
/* dynamically memory allocated*/
scope =(char*) malloc( 100 * sizeof(char) );
if( scope == NULL ) {
printf( "Unable to allocate memory\n");
}else {
strcpy( scope, "Share and Support the Onlinetpoint.com");
}
printf("Name: %s\n", name );
printf("Scope: %s\n", scope );
free(scope);// release the allocated memory
}
Allocating memory from the heap with insufficient memory is called overflow and calling malloc function with zero sizes may return a null pointer or other value.
calloc( ):
The calloc() function is used to seeking memory space at the runtime for storing derived data types such as arrays and structures. The calloc function allocates multiple blocks of storage each of the same size and then sets all bytes to zero. Declaration of calloc( ) is:
void * calloc(size_t element-count , size_t element-size);
It works similar to malloc when overflow and when zero size is given.
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com