Introduction
We will discuss in the article, what are the use of malloc() and calloc() functions in c? In which header file these two functions are defined.
Getting Started
malloc() and calloc() are dynamic allocation functions in c.
In array declaration, it is a static allocation of memory. Before the execution of program, we have to allocate the memory, which may be totally used or may not be used.
Memory allocation in c is done by malloc() and calloc() through a pointer variable.
malloc() and calloc() are just like a request to RAM to allocate memory in bytes. If the request is granted, then the pointer is assigned with the address of base address.
By incrementing the pointer variable value we can go to the next memory allocations.
malloc() and calloc() function is assigned by a pointer variable of the defined data type.
malloc() and calloc() return void pointers. So we have to type cost the function to a pointer variable of defined datatype.
malloc() and calloc() are defined in
header file. By default malloc() returns grabage value, where as calloc() returns zero output.
Syntax
malloc syntax:- malloc() needs a pointer variable of allocation of memory.
void *malloc( size_t size ); //invoke syntax int *p p=(int*)malloc(n*sizeof(int));
calloc syntax : it is the same as malloc(), the only difference is that it needs two variables of defining a function.
void *calloc( size_t number, size_t size ); //invoke syntax long *buffer; buffer = (long *)calloc( 40, sizeof( long ) );
Difference between malloc and calloc: Both malloc and calloc functions are dynamic memory allocation function. malloc uses one argument where as calloc uses two arguments. malloc returns grabage value where as calloc returns zero value as output by default.
Thanks