C language

Functions to manage heap memory

The functions to manage heap memory which are included in the directory  #include <stdlib.h> are:

 malloc():

void * malloc (size_t size);

As we see from the prototype of the malloc function that we have to pass the number of bytes required as parameter to the malloc function and the function returns the starting address of the allocated apace as void pointer. As the void pointer is returned hence we have to typecast the pointer as the type we require. E.g.

If we need 6 bytes for intergers we type cast the memory as

Int* x;

x=(int*)malloc(6);

If we are storing char variables in the allocated space then we do as:

Char* y;

y=(char*)malloc(6);

calloc():

The prototype of the function is as:

void * calloc (size_t nr, size_t size);

nr is number of variables of the required type and size is the number of bytes required for that type

and this function automatically initializes the memory allocated to zero.

e.g.

if we need memory for 6 integers

int* x;

x=(int*)calloc (6, sizeof(int) );

 if we need memory for 6 characters

char* x;

x=(char*)calloc (6, sizeof(char) );

NOTE: If any of the two functions is not able to allocate memory then it returns a NULL pointer.

realloc():

The prototype of the realloc() function is

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

This function is used to redefine the size already allocated. Suppose as I have already allocated memory for 6 integers in the previous example, now I want the space for the 8 integers then I do as:

X= (int*)realloc (x,8) ;

Free():

The prototype of the free() function is

void* free (void* ptr);

We write the following to free the memory of x:

free(x);

3 Replies to “Functions to manage heap memory

Leave a Reply

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