Site icon i2tutorials

Dynamic Memory Allocation

Dynamic Memory Allocation

 

For example, if we have to store only 50 values in an array of size 200, then the space for 150 values ie, 600 bytes will be wasted.

Similarly, if we want to store 250 values in the array of size 200 that is also not possible.

To overcome those problems, we should be able to allocate memory at run time.

The memory allocation process when running is called dynamic memory allocation.

The allocation and release of this memory space can be done with some built-in functions which are present in the header file “stdlib.h”.

Pointers play a big part in dynamic memory allocation because we can only access dynamically allocated memory by pointers.

The following are the functions that are used in dynamic memory allocation.

i. Malloc()

ii. Calloc

iii. Realloc()

iv. Free()

 

Malloc :

 

This is used to allocate memory dynamically.

 

void * malloc(size_t sixe);
Int * ptr;
Ptr = (int *) malloc(12);
Ptr = (int *) malloc(5 * sizeof(int));

 

Calloc :

 

This is used to allocate multiple blocks of memory.

 

void * calloc(size_t n, size_t size);

 

Realloc() :

 

This is used to increase or decrease the memory allocated by malloc() or calloc() functions.

 

void * realloc(void * ptr, size_t new_size);

 

Free() :

 

This is used to release the memory space allocated dynamically.

 

void free ( void * p);

 

Exit mobile version