C Language: Pointers 24

malloc()

This function helps us to allocate a block of memory dynamically of specified size and returns back the pointer of type void which can be stored in a pointer variable of any data type.

Syntax:

datatype *pointervariable;
pointervariable= (cast type) malloc (size);

Example:
To allocate memory dynamically for storing 10 integers.

int *p;
p=(int*)malloc(10*sizeof(int));
p=(int*)malloc(50);

To allocate memory dynamically for storing 10 characters

char *p;
P=(char*)malloc(10*sizeof(char));
Or
P=(char*)malloc(10);

As size of char is 1 byte.

In general to allocate memory dynamically for n integers

int n,*p;
printf(“Enter total elements “);
scanf(“%”,&n);
p=(int*)malloc(n*sizeof(int));

Before using the memory block which has been allocated dynamically it is very important to verify whether the memory has been successfully allocated or not. If memory is successfully allocated then base address of the allocated memory block is returned back and stored in the pointer variable. On the other hand if memory allocation fails then NULL is returned back and stored in the pointer variable.


int n,*p;
printf (“Enter total elements “);
scanf (“%”,&n);
p= (int*) malloc(n*sizeof(int));
if (p==NULL)
{
printf (“memory allocation failed”);
return;
}

 

free()

This function helps us to release the memory block which has been allocated dynamically using either malloc() or calloc() function.

Syntax:
free(pointervariable);

Example :
free(p);

Note: Releasing the memory block using free() function is an indication to the system that the specified memory is no longer required and if any other process needs memory then this memory block can be given to it.
Note: illegal pointer should not be given as an argument system may crash.