0

In dynamically allocating memory for a struct, I ran across some code that does

struct simulation *sim_one = calloc(1, sizeof(*sim_one));

Is there any reason to prefer using calloc over malloc for structs? In this context, do they do the same thing? Also, I've only ever seen sizeof called with a datatype; however, the calloc example calls sizeof on a pointer to a variable sim_one which, I would think, doesn't exist at the moment when sizeof is called, but compilation and execution leads to no errors. See below for the malloc example.

struct simulation *sim_two = malloc(sizeof(struct simulation));

The latter option is syntax for which I am familiar from allocations such as double *var = malloc(sizeof(double)).

I define the structs here for clarity:

struct particle {
  double x;
  double y;
  double z;
};

struct simulation {
  struct particle particles[100];
};

int main(){
  struct simulation *sim_one = calloc(1, sizeof(*sim_one));       // why?
  struct simulation *sim_two = malloc(sizeof(struct simulation)); // familiar malloc syntax
}
Jared Frazier
  • 413
  • 1
  • 4
  • 10
  • Too often `xxx *p = malloc( sizeof( xxx ) );` is overlooked when 'p' is changed to point to 'yyy'... The new-to-you version `xxx *p = malloc( sizeof *p );` has less maintenance and less chance for overlooking the required change when `yyy *p = malloc....` is required. – Fe2O3 Jan 11 '23 at 22:16
  • PS: `sizeof` is a compile time operator. It is not a runtime function that is "_called_." – Fe2O3 Jan 11 '23 at 22:18
  • @Jared Frazier, With `struct simulation *sim_one = calloc(1, sizeof(*sim_one));`, `sim_one` exist at the end of `struct simulation *sim_one`, so " variable `sim_one` which, I would think, doesn't exist at the moment when sizeof is called," is amiss. – chux - Reinstate Monica Jan 11 '23 at 22:34
  • @Jared Frazier, I recommend you use the `pointer = malloc(sizeof pointer[0] * n)` syntax. It is easier to code right, review and maintain than `pointer = malloc(n * sizeof (*pointer_type))`. – chux - Reinstate Monica Jan 11 '23 at 22:37

0 Answers0