Dynamic Memory Allocation C Tutorial

 

Bodhak dynamic memory allocation c tutorial in this chapter let us learn about Introduction to Dynamic memory allocation, Advantages of DMA,  Working with malloc() calloc () realloc () free() functions, creating dynamic arrays,  creating dynamic structures, creating a dynamic array of structures, DMA using functions.

Dynamic Memory Allocation: When we are declaring an array we must specify the size of the array and this must be a constant integral expression only.

 

 

dynamic memory allocation c tutorial

we can’t change the array size of an array during program execution. This is because for arrays the memory will be allocated at the compile time and this kind of memory is known as static memory allocation.

This is because for arrays the memory will be allocated at the compile time and this kind of memory is known as static memory allocation.

If we are allocating the memory at run time then we call it dynamic memory allocation.

Through, dynamic memory allocation we are using heap memory which is an unnamed memory. Hence to access this memory we must use pointers.

Hence to access this memory we must use pointers.

To implement dynamic memory allocation we may use the following functions:

 

1) malloc ()

2) Calloc ()

3) realloc ()

4) free ()

 

The malloc () function is used to allocate the memory at the run time. for this function, we need to pass the number of bytes as an argument. if the memory allocation is successful then it will return the starting address of the allocated memory space,

For this function, we need to pass the number of bytes as an argument.

If the memory allocation is successful then it will return the starting address of the allocated memory space,

if the memory allocation is successful then it will return the starting address of the allocated memory space, otherwise, it will return a value NULL.

 

The return value of malloc() function is void

 

Syntax:

void * malloc(<size>);

We can allocate memory during run time using the calloc() function

 

For this function we need to pass 2 arguments:

1)A number of elements.

2)size of each element.

 

The memory allocation by malloc() function contains garbage values where as memory allocation by calloc() function contains 0’s.

 

Syntax:

void * calloc(<count>,<data size>);

We can reallocate the memory space by using the realloc() function.

 

For this, the function needs to pass 2 arguments.

1)A pointer to the existing memory space.

2)the total memory size in bytes after reallocation.

 

We can reconstruct the memory block with new size by using realloc() function.

 

 

Syntax:

void* realloc(<ptr>,<new size>);