I’m not sure the proper way to handle the casting of types when using malloc. I’m coming from Objective C where the following is perfectly legal:
ALuint * sources;
sources=malloc(sizeof(ALuint)*32);
However, in C++ the compiler says “Assigning to ALuint * from incompatible type void *”.
I get that the memory returned from malloc is not casted as my particular type, and I get that C++ is strict with types.
Now, I could do this:
sources=(ALuint*)malloc(sizeof(ALuint)*32);
But I have read much wiser coders than myself say never to cast in such a manner. Why not? And if not, when or how is the best time or method to make this work?
mallocin C++.#1, You must cast the return type ofmallocfor your code to compile.#2is if your target pointer is avoidpointer.mallocis (debatebly)considered as good practice in C.So, In C++ a cast is necessary. The type of cast to use is also important though. It should definitely not be the c-style cast. The above links were demonstration of need of cast only.
Now, I could do this:
But I have read much wiser coders than myself say never to cast in such a manner. Why not?
Because in C++ a c-style cast is defined by the standard to map to C++ cast in following order. The first one to succeed will be used:
As you see a c-styled cast might in fact result in
reinterpret_castwhich is potentially dangerous as it can cast between incompatible pointer types. So if you must usemallocuse: