Why does C++ require a cast for malloc() but C doesn't?


In C language, the void pointers are converted implicitly to the object pointer type. The function malloc() returns void * in C89 standard. In earlier versions of C, malloc() returns char *. In C++ language, by default malloc() returns int value. So, the pointers are converted to object pointers using explicit casting.

The following is the syntax of allocating memory in C language.

pointer_name = malloc(size);

Here,

pointer_name − Any name given to the pointer.

size − Size of allocated memory in bytes.

The following 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 = 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

Enter elements of array : 2 28 12 32
Sum : 74

In the above example in C language, if we do explicit casting, it will not show any error.

The following is the syntax of allocating memory 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.

The following is an example of malloc() in C++ language.

Example

#include <iostream>
using namespace std;
int main() {
   int n = 4, i, *p, s = 0;
   p = (int *)malloc(n * sizeof(int));
   if(p == NULL) {
      cout << "\nError! memory not allocated.";
      exit(0);
   }
   cout << "\nEnter elements of array : ";
   for(i = 0; i < n; ++i) {
      cin >> (p + i);
      s += *(p + i);
   }
   cout << "\nSum : ", s;
   return 0;
}

Output

Enter elements of array : 28 65 3 8
Sum : 104

In the above example in C++ language, if we will not do the explicit casting, the program will show the following error.

error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]
p = malloc(n * sizeof(int));

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

658 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements