Memory Management

Notes Zone
0

 Dynamic Memory Allocation

This procedure is referred to as Dynamic Memory Allocation in C.
Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are: 

  1. malloc()
  2. calloc()
  3. free()
  4. realloc()

C malloc() method

The "malloc" or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn’t Initialize memory at execution time so that it has initialized each block with the default garbage value initially. 

Syntax of malloc() in C

ptr = (cast-type*) malloc(byte-size)


C calloc() method

  1. "calloc" or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. it is very much similar to malloc() but has two different points and these are:
  2. It initializes each block with a default value ‘0’.
  3. It has two parameters or arguments as compare to malloc().

Syntax of calloc() in C

ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.


C free() method

"free" method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.

Syntax of free() in C

free(ptr);

C realloc() method

"realloc" or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-allocation of memory maintains the already present value and new blocks will be initialized with the default garbage value.

Syntax of realloc() in C

ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.





Tags

Post a Comment

0Comments

Post a Comment (0)