DEV Community

Discussion on: Dynamic memory allocation in C

Collapse
 
step_prosperi profile image
Stefano Prosperi

Casting the result of malloc is unnecessary and very bad practice.

Bad:

int * pNumber = (int*) malloc(25*sizeof(int));

Good:

int * pNumber = malloc(25*sizeof(int));
Collapse
 
therselman profile image
therselman • Edited

I think you are wrong about casting malloc is bad practice. You will get a compiler warning if you don't! It's total rubbish that it's bad practice! If you are not getting compiler warnings, then you aren't using a high enough warning level! It's more an inconvenience than anything else, that's why C++ created the Auto keyword, but even then you would need to cast it so that auto can infer the correct type.

Collapse
 
step_prosperi profile image
Stefano Prosperi • Edited

stackoverflow.com/a/605858/9815377

It's important to stress that we're talking about C, not C++

Thread Thread
 
ac000 profile image
Andrew Clayton

Indeed.

I think it is also worth explicitly stating that these days C and C++ are very different languages. (All too often I see people conflating the two or just saying C/C++, when they really mean one or the other...)