Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I cast the result of malloc in C++? [duplicate]

Tags:

c++

Please note this question is not about malloc in C or malloc vs new/smart pointers in C++.

If I use malloc in C++, what kind of cast should I use? The following all work.

int *a = (int *)malloc(sizeof (int));
int *b = static_cast<int *>(malloc(sizeof (int)));
int *c = reinterpret_cast<int *>(malloc(sizeof (int)));

Live example: http://ideone.com/lzfxcm

I prefer to use C++ style casts in my code as much as possible and I want to adopt safe coding habits. Please advise with this in mind.

Thank you.

like image 737
Neil Kirk Avatar asked Sep 25 '13 12:09

Neil Kirk


1 Answers

Since malloc returns a pointer to void, there is no reason to use a C++ - style cast on the pointer: you get a chunk of raw memory, with no structure behind it, so the only thing your can tell the compiler by adding a cast is that you plan to use this memory for data of a particular kind. Compiler must agree with you on that, because it has no additional information to double-check your decision. Neither static_cast<T> nor the reinterpret_cast<T> offer a particular advantage over the C-style cast, and the C-style cast is shorter.

From the personal perspective, I looked at a lot of C++ code, but I've never seen a C++ - style cast used with malloc, only the C-style.

like image 127
Sergey Kalinichenko Avatar answered Oct 05 '22 22:10

Sergey Kalinichenko