malloc casting in C vs C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

malloc casting in C vs C++

Why we need to cast malloc in C++ but it is not a good practice to cast it in C?

10th Apr 2017, 9:50 PM
Aaron Sarkissian
Aaron Sarkissian - avatar
2 Answers
+ 4
The newer C++ is pretty strict in types checking. It essentially says that if you need a pointer to char, then you have to provide a memory location that indeed holds characters and nothing else. In C, the compilers are (or were) generally liberal. The onus of providing correct types is on the developer alone. This caused problems. So to eliminate it, strict type checking was recommended. As a side note, you can use void * as it'll generate a warning alone. Read more about compiler flags, it's helpful :-)
11th Apr 2017, 9:05 AM
Renjith M
Renjith M - avatar
+ 4
Thank you!
11th Apr 2017, 9:43 AM
Aaron Sarkissian
Aaron Sarkissian - avatar