0

Why do we cast malloc, as in the following?

ptd = (double *) malloc(max * sizeof(double));

What is malloc's normal return type? Why do we need to cast it?

user3897320
  • 87
  • 1
  • 2
  • 7
  • The return type is a `void *`. You don't *have* to cast it. – Austin Brunkhorst Aug 02 '14 at 04:21
  • @AustinBrunkhorst So to confirm, I **SHOULDN'T** cast it? The above would just become `ptd = malloc(max * sizeof(double));`? The author of this book casted it but has yet to explain exactly why. Why shouldn't it be cast? If it matters, `double *ptd` is where `ptd` is declared. – user3897320 Aug 02 '14 at 04:40
  • 2
    This is actually a question to you. Why really do you cast it? There's absolutely no reason to do it and it can actually be harmful. **Don't** cast the result of `malloc`. A good idiomatic form of `malloc` expression, applied to your example, would be `ptd = malloc(max * sizeof *ptd)`. – AnT stands with Russia Aug 02 '14 at 04:40
  • @AndreyT thanks, that looks good. So _never_ cast it? – user3897320 Aug 02 '14 at 04:46
  • Never cast it. Except in rare situations, a cast in C is an indication that you're doing something *wrong*. This is especially the case if the type you're casting from or to is a pointer type. – R.. GitHub STOP HELPING ICE Aug 02 '14 at 04:50

2 Answers2

0

This is malloc prototype

void *malloc(size_t size);

Generally no need to do typecasting.

mahendiran.b
  • 1,315
  • 7
  • 13
0

From a standard guide:

Declaration:

void *malloc(size_t size);

Allocates the requested memory and returns a pointer to it. The requested size is size bytes. The value of the space is indeterminate. On success a pointer to the requested space is returned. On failure a null pointer is returned.

That should be everything!

fingaz
  • 241
  • 1
  • 6