Do You Need to Typecast Malloc?

Do You Need to Typecast Malloc?

In C, you don't need to cast the return value of malloc . The pointer to void returned by malloc is automagically converted to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed.

Why do we typecast malloc?

The cast allows for pre-1989 versions of malloc that originally returned a char * . Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from the malloc() call.

Do I need to memset after malloc?

Do I need to memset twice too? Technically no, provided you properly initialize all elements of the Buffer struct before using them. I feel this is a risky habit, however. It's very difficult to be consistent, and in some contexts the program can crash if you make a mistake.

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.