Correct ways and Best way to malloc a struct?

I've seen different ways to malloc a struct, but I'm confused which way is the best way to do it. (Please add explanations when your give your opinions.)

The code below uses a variable's type as size in malloc().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct Vector {
    double *data;    
    size_t size;
};

int main()
{
  int sz = 12;

  struct Vector *retVal = malloc (sizeof (struct Vector)); //#####
  retVal->data = malloc (sz * sizeof (double));            //#####
 
  // Set size and return.
  retVal->size = sz;
  printf("retVal->size: %d\n", sz);

  return 0;
}


However, the two lines using malloc() marked w/ "//#####" can be replaced by the following ways and get compiled and printed out the correct value:
(1)
struct Vector *retVal = malloc (sizeof (struct Vector *)); //#####
retVal->data = malloc (sz * sizeof (double *)); //#####
(2)
struct Vector *retVal = malloc (sizeof (retVal)); //#####
retVal->data = malloc (sz * sizeof (retVal->data)); //#####
(3)
struct Vector *retVal = malloc (sizeof (*retVal)); //#####
retVal->data = malloc (sz * sizeof (retVal->data)); //#####

My questions: Are all the 4 methods correct? Which way is the best way?

Thanks in advance for your help!
Last edited on
closed account (48T7M4Gy)
http://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new
You can do a small experiment.
Checkout the sizes.

sizeof(struct Vector)
sizeof(struct Vector*)
sizeof(retVal)
sizeof(*retVal)

sizeof(12 * sizeof(double))
sizeof(12 * sizeof(double*))
sizeof(12 * sizeof(retVal->data))

And then you could get the answer.
The three alternative snippets are incorrect.
@kemort, I forgot to mention I'm using only C.

@helios, I was told specially to use (3) over the other 3 methods since it's both correct and more convenient when the variable type needs to be changed. Could you explain why it's not correct? Thanks.
Last edited on
sizeof(retVal->data) is sizeof(double *), which may be different from sizeof(double).
Topic archived. No new replies allowed.