Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does struct Node *ptr = malloc(sizeof(*ptr)) work?

I'm a C beginner, and I came across this code while trying to implement a linked list.

    struct Node *ptr = malloc(sizeof(*ptr));

The Node struct looks like this:

    struct Node {
        int data;
        struct Node *next;
    };

I'm trying to understand the first line. It seems as if malloc(sizeof(*ptr)) already knows the contents of ptr. What exactly is happening on the left side and is it happening before malloc is called?

like image 342
wrosen01 Avatar asked Jul 25 '26 07:07

wrosen01


2 Answers

It seems as if malloc(sizeof(*ptr)) already knows the contents of ptr.

Actually, it doesn't. The sizeof operator doesn't actually evaluate its operand (unless it's a variable length array), it just looks at its type. This means that ptr isn't actually dereferenced and is therefore a safe operation.

like image 199
dbush Avatar answered Jul 28 '26 06:07

dbush


Only use paranthesis with sizeof if there's a type you'd like to know the size of. If you have an expression, like *ptr, it's enough to write:

struct Node *ptr = malloc(sizeof *ptr);         // <- no parenthesis

The expression *ptr dereferences the pointer so it becomes a struct Node and that's what the sizeof is returning the size for.

sizeofexpression - Returns the size, in bytes, of the object representation of the type of expression. No implicit conversions are applied to expression.

It's the same size you get if you do:

struct Node *ptr = malloc(sizeof(struct Node)); // <- parenthesis needed

but the first alternative is often preferable for clarity.

like image 29
Ted Lyngmo Avatar answered Jul 28 '26 04:07

Ted Lyngmo