How do malloc() and free() work in C/C++?

C++ProgrammingServer Side Programming

malloc()

The function malloc() is used to allocate the requested size of bytes and it returns a pointer to the first byte of allocated memory. It returns null pointer, if it fails.

Here is the syntax of malloc() in C language,

pointer_name = (cast-type*) malloc(size);

Here,

  • pointer_name  − Any name given to the pointer.

  • cast-type  − The datatype in which you want to cast the allocated memory by malloc().

  • size  − Size of allocated memory in bytes.

Here is an example of malloc() in C language,

Example

 Live Demo

#include <stdio.h>
#include <stdlib.h>

int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) malloc(n * sizeof(int));
   
   if(p == NULL) {
      printf("\nError! memory not allocated.");
      exit(0);
   }
   printf("\nEnter elements of array : ");

   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\nSum : %d", s);
   return 0;
}

Output

Here is the output

Enter elements of array : 32 23 21 8
Sum : 84

free()

The function free() is used to deallocate the allocated memory by malloc(). It does not change the value of the pointer which means it still points to the same memory location.

Here is the syntax of free() in C language,

void free(void *pointer_name);

Here,

  • pointer_name − Any name given to the pointer.

Here is an example of free() in C language,

Example

 Live Demo

#include <stdio.h>
#include <stdlib.h>

int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) malloc(n * sizeof(int));

   if(p == NULL) {
      printf("\nError! memory not allocated.");
      exit(0);
   }
   printf("\nEnter elements of array : ");

   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\nSum : %d", s);
   free(p);
   return 0;
}

Output

Here is the output

Enter elements of array : 32 23 21 28
Sum : 104
raja
Published on 24-Oct-2018 12:53:20
Advertisements