MALLOC and CALLOC in C

Kailash Chandra Behera | Saturday, November 28, 2020

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

  1. malloc() and calloc() are dynamic allocation functions in c.

  2. 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.

  3. Memory allocation in c is done by malloc() and calloc() through a pointer variable.

  4. 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.

  5. By incrementing the pointer variable value we can go to the next memory allocations.

  6. malloc() and calloc() function is assigned by a pointer variable of the defined data type.

  7. malloc() and calloc() return void pointers. So we have to type cost the function to a pointer variable of defined datatype.

  8. malloc() and calloc() are defined in header file.

  9. By default malloc() returns grabage value, where as calloc() returns zero output.

  10. Syntax

    1. 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));  
      
    2. calloc syntax : it is the same as malloc(), the only difference is that it needs two variables of defining a function.

    3.  void *calloc(  
         size_t number,  
         size_t size  
       );  
       //invoke syntax  
       long *buffer;  
        buffer = (long *)calloc( 40, sizeof( long ) );  
      
  11. 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


No comments: