1

I want to know what is the difference between these two lines :

 queue* f=(queue*)malloc(sizeof(queue));
 queue* f=(queue*)malloc(sizeof(queue*));

Here's the definition of queue:

typedef struct queue
{
    int arr[N];
    int tail;
}queue;

Thanks in advance!

LEARNER
  • 123
  • 1
  • 9
  • 2
    The supposed "duplicate" is about casting, but the key issue here is the size. Voting to reopen. – Nate Eldredge May 31 '20 at 16:00
  • @NateEldredge It is, but the first answer explains why you in this case should not use neither form, but instead `malloc(sizeof *f)` – klutt May 31 '20 at 16:02
  • @NateEldredge: Yeah, I suspect someone saw that the other question was associated because I linked it in my answer, but it's not a duplicate at all. – ShadowRanger May 31 '20 at 16:02
  • But ok, here you have a perfect dup: https://stackoverflow.com/questions/24363427/what-is-the-difference-between-mallocsizeofint-and-mallocsizeofint – klutt May 31 '20 at 16:08
  • Does this answer your question? [What is the difference between malloc(sizeof(int)) and malloc(sizeof(int\*))](https://stackoverflow.com/questions/24363427/what-is-the-difference-between-mallocsizeofint-and-mallocsizeofint) – ShadowRanger May 31 '20 at 16:30
  • why did you not accepted the answer of @ShadowRanger ? (may be you just forgot to do) – bruno Aug 20 '20 at 08:30
  • 1
    @bruno because at that time i didn't have enough points to give him the best answer, but now i do, thank you for reminding me – LEARNER Aug 22 '20 at 01:18

1 Answers1

7

The difference is that the second line is wrong; it allocates enough space to store a pointer to a queue, not a queue itself, but it's assigned to a type that assumes it points to enough space for a whole queue.

Neither one requires a cast, so the correct form is:

queue *f = malloc(sizeof(queue));

To be even safer, don't refer to the type itself, refer to the variable you're assigning to, to avoid repeating the type (potentially causing maintenance problems if the type is changed); this also means sizeof doesn't need parentheses:

queue *f = malloc(sizeof *f);
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • `sizeof` requires parentheses if the operand is a type name like `int` or a typedef name like `queue`. – John Bode May 31 '20 at 17:22
  • @JohnBode: Ah, you're right. I'm so used to using the `*f` form I forgot the rule for naming the type itself. Fixed, and linked to the question that covers the rule. – ShadowRanger May 31 '20 at 22:15