2

This post says that one should cast malloc in C++, but should not in C. AFAIK they both are strictly typed. Why is there such difference between C and C++ concerning casting malloc or calloc?

Kaiyakha
  • 1,463
  • 1
  • 6
  • 19
  • Does this answer your question? [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Mark Benningfield Dec 08 '20 at 11:13
  • 1
    The link you provide answers the C part of your question in details. – YSC Dec 08 '20 at 11:13
  • 4
    For the C++ part: don't call malloc – YSC Dec 08 '20 at 11:13
  • 1
    "strictly" typed means different things in different contexts (languages). C is not really strictly typed but rather has a set of rules of what is checked and what is not and what yields undefined behavior. While many hardcore C programmer hate me saying this, you can write your C code such, that it compiles as well if compiled with a C++ compiler. If you want to do that, you should add the cast. Else, you can omit it. – BitTickler Dec 08 '20 at 11:14
  • The question linked to (the same as that I linked to) does not explain why there is such difference – Kaiyakha Dec 08 '20 at 11:15
  • 3
    1. Study the C question, whereupon it's apparent you *shouldn't* cast although if you do it will have a benign effect if you've `#include`d the correct files. 2. The C++ answer is easier, you *must* cast else your code won't compile. – Bathsheba Dec 08 '20 at 11:16
  • 1
    @Ch3steR this one does, thanks – Kaiyakha Dec 08 '20 at 11:19
  • Actually, the question should be: "Why not to cast malloc in C whereas not use malloc in C++?" ;-) – Scheff's Cat Dec 08 '20 at 12:02
  • The `*alloc` functions return `void *`. C allows you to assign `void *` to other pointer types without a cast - C++ does not. Thus in C++ you need to cast the result of `*alloc` if the target is not a `void *`. In C the cast is redundant, and is often a source of error (and under C89 could suppress a useful warning if you forgot to include `stdlib.h`). As a rule you should not use `*alloc` in C++ - either use containers that do memory management for you, or use the `new` and `delete` operators. – John Bode Dec 08 '20 at 12:05

0 Answers0