Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

c++ - Needless pointer-casts in C

I got a comment to my answer on this thread:

Malloc inside a function call appears to be getting freed on return?

In short I had code like this:

int * somefunc (void)
{
  int * temp = (int*) malloc (sizeof (int));
  temp[0] = 0;
  return temp;
}

I got this comment:

Can I just say, please don't cast the return value of malloc? It is not required and can hide errors.

I agree that the cast is not required in C. It is mandatory in C++, so I usually add them just in case I have to port the code in C++ one day.

However, I wonder how casts like this can hide errors. Any ideas?

Edit:

Seems like there are very good and valid arguments on both sides. Thanks for posting, folks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It seems fitting I post an answer, since I left the comment :P

Basically, if you forget to include stdlib.h the compiler will assume malloc returns an int. Without casting, you will get a warning. With casting you won't.

So by casting you get nothing, and run the risk of suppressing legitimate warnings.

Much is written about this, a quick google search will turn up more detailed explanations.

edit

It has been argued that

TYPE * p;
p = (TYPE *)malloc(n*sizeof(TYPE));

makes it obvious when you accidentally don't allocate enough memory because say, you thought p was TYPe not TYPE, and thus we should cast malloc because the advantage of this method overrides the smaller cost of accidentally suppressing compiler warnings.

I would like to point out 2 things:

  1. you should write p = malloc(sizeof(*p)*n); to always ensure you malloc the right amount of space
  2. with the above approach, you need to make changes in 3 places if you ever change the type of p: once in the declaration, once in the malloc, and once in the cast.

In short, I still personally believe there is no need for casting the return value of malloc and it is certainly not best practice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...