0

Here's a code snippet that runs ok:

struct person *ptr;
ptr = malloc(n * sizeof(struct person));

But on many C websites the second line is written as

ptr = (struct person*) malloc(n * sizeof(struct person));

My questions are: Is it wrong to NOT explicitly mention the type during such malloc() statements? Why should I explicitly mention the type during such statements?

devolskii
  • 27
  • 7
  • 1
    this question has been answered here: https://stackoverflow.com/q/605845/5639126 – secret squirrel Jul 27 '20 at 20:46
  • Note that even better would be `ptr = malloc(n * sizeof *ptr);` or even `ptr = calloc(n, sizeof *ptr);` (the latter avoiding the need to check for overflow in advance). – R.. GitHub STOP HELPING ICE Jul 27 '20 at 20:56
  • @R..GitHubSTOPHELPINGICE I'm a beginner. What is overflow here and how does ```calloc``` stop it? – devolskii Jul 27 '20 at 21:05
  • Depending on the value of `n`, there's no guarantee that the arithmetic result of `n * sizeof *ptr` is representable; if not it wraps (since `size_t` is an unsigned type). You have to check that yourself unless you have a prior bounds on `n` that make the overflow impossible. With `calloc`, you're able to request a product that would overflow and it necessarily fails (since it can't be satisfied). – R.. GitHub STOP HELPING ICE Jul 27 '20 at 21:13

0 Answers0