Monday, 13 April 2020

Dynamic memory allocation in C language with example


Dynamic memory allocation in C is performed using one of the standard library functions
malloc, calloc or realloc. Dynamically allocated memory must eventually be freed by calling free. If allocated memory is not properly freed a memory leak results, which could result in a program malfunction.
All these functions are in header file <stdlib.h>.

The malloc() function
This function allocates specified number of bytes.
It takes a single argument.
It does not initialize the allocated memory.
It returns a pointer of type void which can be cast into a pointer of any form.
If space is insufficient, allocation fails and returns a NULL pointer.
Syntax:
    ptr=(cast_type *) malloc(sizeof(type))

Example:
   int *ptr;
   ptr=(int *) malloc(sizeof(int));

   ptr points to memory allotted by malloc() function.

The calloc() function
This function allocates specified number of bytes.
It takes two arguments.
It initializes each block allocated memory with a default value of 0.
It returns a pointer of type void which can be cast into a pointer of any form.
If space is insufficient, allocation fails and returns a NULL pointer.
Syntax:
    ptr=(cast_type *) calloc(n,sizeof(type))
   where
      n= no of elements
      sizeof(type) return no of bytes to be allotted

Example:
   int *ptr;
   ptr=(int *) calloc(n,sizeof(int));

ptr points to memory allotted by calloc() function.


The realloc() function
If someone wants to modify the memory allotted by malloc() and calloc() functions, this function can be used to do this.
Syntax:
  ptr=(cast_type*) realloc(ptr,sizeof(type))

Example:
   int *ptr;
   ptr=(int *) malloc(sizeof(int));

   ptr=(int*) realloc(ptr,newSize);

The free() function
Memory allotted using malloc() and calloc() functions should be freed. It helps to reduce wastage of memory.
Syntax:
  free(pointer_variable);

Example:
   int *ptr;
   ptr=(int *) malloc(sizeof(int));

  free(ptr);


You may also like:
 Structure in C
 Typedef in C with examples
 Array of Structures in C with Example
 Self Referential Structures in C
 Passing structure to a function in C with example

Please comment and share if you find it useful.

No comments:

Post a Comment