Dynamic Memory Allocation malloc vs calloc - WBUT MCA 2011
softetechnologies
25-11-2019    174 times
Dynamic Memory Allocation malloc calloc WBUT MCA

What do you mean by dynamic memory allocation? Critically compare between malloc() and calloc() functions. [WBUT MCA 2011]

In a C program, we used various variables or arrays of primitive data types. When we declare such variables, the program assigns a predefined amount of memories and we cannot change the amount of the memories for that variable. i.e. Static Memory Allocation. But in some real life application may need to change the amount of memory regularly in real application may need to change the amount of memory regularly at real time.

E.g. create a name field for a banking project. Here we don’t know what will be the length of the name of a customer. If we get a char array for the name which length is 10. The it may too short for a south Indian customer. And also if we set the length of the variable is 100, then huge memory loss of most the customers.

To solve this problem C language uses some methods, like malloc(), calloc(), free(), realloc() to allocate memory at run time as per required. This type of memory allocation is known as Dynamic Memory Allocation which the size is changed during the runtime.

Private Teacher

malloc()

To allocate a specified size of memory block at runtime or dynamically, we use malloc(). Malloc is stands for memory allocation. It returns a pointer of type void. We can cast this pointer into any type or form.

Syntax:

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

Example:

ptr = (int*) malloc(400);

This statement will allocate 400 bytes of memory. And *ptr hold the memory location or address of the first byte.

Tutorial at home
Tutorial at home

calloc()

To allocate a numbers of memory block of specified size at runtime or dynamically, we use calloc(). Calloc is stands for contiguous allocation. It returns a pointer of type void. We can cast this pointer into any type or form.

Syntax:

ptr = (cast-type *) calloc(n,byte-size)

Example:

ptr = (int*) calloc(2,400);

This statement allocates contiguous space in memory for 2 elements each with the size of the 400 bytes that is total 800 bytes.

softetechnologies
softetechnologies
    Author Details
Arnab De
I have over 16 years of experience working as an IT professional, ranging from teaching at my own institute to being a computer faculty at different leading institute across Kolkata. I also work as a web developer and designer, having worked for renowned companies and brand. Through tutorialathome, I wish to share my years of knowledge with the readers.
    Related Post
  Query About the post