Question

I've got a rather unusual question. I've seen two variants of passing arguments to malloc. Let's say we've got:

int *arr = (int *) malloc(sizex * sizeof(*arr));

Some people say that using sizeof(*arr) is bad and you should use sizeof(int) (in this example) instead. Could you explain what's the difference and what's better to use?

Was it helpful?

Solution

There is no difference. Both allocate the same amount of memory -

int *arr = (int *) malloc(sizex * sizeof(*arr));
// equivalent to
int *arr = (int *) malloc(sizex * sizeof(int));

However, there are some things to note.

  1. You should not cast the result of malloc. It's not useful and can actually cause problems if you forget to include the header stdlib.h which contains its prototype. Please read this - Do I cast the result of malloc?

  2. I prefer the first version above because there's no repetition of the type information. Also, it's more maintainable in the sense that if you change the type, then you need to change it only once where as in the second case, you need to change it in two places.

It should be noted that sizeof needs parentheses for its operand only when it's a type. Therefore, it can be written more succinctly as

int *arr = malloc(sizex * sizeof *arr); 
// equivalent to
int *arr = malloc(sizex * sizeof(*arr));  // preferred way
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top