Explain Dynamic Memory Allocation in Detail

Dynamic Memory Allocation

The Dynamic memory allocation enables the allocation of memory at runtime.

Malloc()

Malloc() is used to allocate a block of memory in bytes at runtime.

If there is insufficient memory to make the allocation, the returned value is NULL.

Syntax:
Where,

data_type *x;
x= (data_type *) malloc(size);


x is a pointer variable of data_type
size is the number of bytes

Example:

int *ptr;
ptr = (int *) malloc(100*sizeof(int));

Calloc( )

Calloc( ) is used in allocating continuous blocks of memory at run time.

If there is insufficient memory to make the allocation, the returned value is NULL.

Syntax:
Where,

data_type *x;
x= (data_type *) calloc(n, size);

x is a pointer variable of type int
n is the number of blocks to be allocated
size is the number of bytes in each block

Example:

int *x
x= calloc (10, sizeof(int));

The above example is used to define a one-dimensional array of integers. The capacity of this array is n=10 and x [0: n-1] (x [0, 9]) are initially 0

realloc( )

Realloc( ) is used for reduce (or) extend the allocated memory.

  • Before using the realloc( ) function, the memory should have been allocated using malloc( ) or calloc( ) functions.
  • The function relloc( ) resizes memory previously allocated by either mallor or calloc, which means, the size of the memory changes by extending or deleting the allocated memory.
  • If the existing allocated memory need to extend, the pointer value will not change.
  • If the existing allocated memory cannot be extended, the function allocates a new block and copies the contents of existing memory block into new memory block and then deletes the old memory block.
  • When realloc is able to do the resizing, it returns a pointer to the start of the new block and when it is unable to do the resizing, the old block is unchanged and the function returns the value NULL

Syntax:

data_type *x; 

x= (data_type *) realloc(p, s );

The size of the memory block pointed at by p changes to S.

When s > p the additional s-p memory block have been extended and when s < p, then p-s bytes of the old block are freed.

Free( )

Dynamically allocated memory with either malloc( ) or calloc ( ) does not return on its own.
The programmer must use free( ) explicitly to release space.

Syntax:

free(ptr);

This statement cause the space in memory pointer by ptr to be deallocated

Leave a Reply

Your email address will not be published. Required fields are marked *