Allocation of memory using the heap

We have four functions for the allocation of memory utilising the heap:

  • Malloc
  • Calloc
  • Realloc
  • Free

malloc():

  • Memory allocation is referred to as malloc. It asks memory from the heap and returns a reference to the memory, as implied by its name. We can typecast the pointer for any variables because it is of the void type. At the time of allocation, all values are initialised to null values. Its syntax is straightforward because we only need to specify the memory space and the desired size in bytes.

Syntax:

ptr = (ptr-type*) malloc(size_in_bytes)

Example:

int *ptr;
ptr = (int*) malloc (3* sizeof(int))

calloc():

  • Contiguous allocation is referred to as calloc. The two key distinctions are that it also asks for memory from the heap, returns a pointer to the memory, and has the same functionality as malloc(). The required number and size of blocks must be sent as parameters. The second distinction is a significant one. In other words, calloc() initialises the variables to 0 rather than a trash value at the moment of allocation.

Syntax:

ptr = (ptr-type*) calloc(n,size_in_bytes) ptr = (ptr-type*) calloc(n,size_in_bytes)

Example:

int *ptr;
ptr = (int*) malloc (10, sizeof(int))

realloc():

  • Reallocation is the definition of realloc. It is employed when dynamic memory is insufficient or when extra memory needs to be allocated in order to hold more data. Its syntax is straightforward because all we have to do is provide the information relating to the pointer while overwriting the memory that has already been allocated as a function parameter.

Syntax:

ptr = (ptr-type*) realloc(ptr,new_size_in_bytes)

Example:

ptr = (int*) realloc (ptr, 5* sizeof(int))

Free():

  • As was said earlier when discussing the drawbacks of dynamic memory allocation, there is no automatic method for releasing the memory space that has been allocated. Therefore, the allocated memory’s space is released using the free function. Since we must send the pointer as a parameter inside the function, its syntax is the simplest of all.

Syntax:

free(ptr)
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in