Search code examples
cpointersdynamic-memory-allocation

Difference between malloc(sizeof(ptr)) and malloc(sizeof(ptr*))?


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!


Solution

  • 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);