What functions are used for dynamic memory allocation in C language?

C Programming Language >   Dynamic Memory Allocation >   Introduction to DMA  

Long Question

641


Answer:

malloc()

      • The malloc() function is used to allocate the memory during the execution of the program.
      • It does not initialize the memory but carries the garbage value.
      • It returns a null pointer if it could not be able to allocate the requested space.

Syntax


ptr = (cast-type*) malloc(byte-size) // allocating the memory using malloc() function.  

calloc()

      • The calloc() is same as malloc() function, but the difference only is that it initializes the memory with zero value.

Syntax


ptr = (cast-type*)calloc(n, element-size);// allocating the memory using calloc() function. 

realloc()

      • The realloc() function is used to reallocate the memory to the new size.
      • If sufficient space is not available in the memory, then the new block is allocated to accommodate the existing data.

Syntax


ptr = realloc(ptr, newsize); // updating the memory size using realloc() function.  

In the above syntax, ptr is allocated to a new size.

free()

The free() function releases the memory allocated by either calloc() or malloc() function.

Syntax


free(ptr); // memory is released using free() function.  

The above syntax releases the memory from a pointer variable ptr.


This Particular section is dedicated to Question & Answer only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.