I am confused about a function dictCreate() in file dict.c of redis implementation. I am going to paste the code here:
/* Create a new hash table
* T = O(1)
*/
dict *dictCreate(dictType *type, void *privDataPtr) {
dict *d = zmalloc(sizeof(*d));
_dictInit(d, type, privDataPtr);
return d;
}
variable d is used in zmalloc(sizeof(*d)), but theoretically it will exist when this line was executed. So my question is how it is possible to use variable d before it is declared?
sizeof is not a function, it is an operator. It is executed (evaluated, to be exact) at compile time, so the scope or lifetime you're thinking about d, does not apply here. All it needs to know is the type of *d and that is known at compile time. Sufficient.
The statement
dict *d = zmalloc(sizeof(*d));
is equivalent to
dict *d;
d = zmalloc(sizeof(*d));
So, dict *d declares d as a pointer to dict type and = zmalloc(sizeof(*d)); used for initialization. dict *d = zmalloc(sizeof(*d)); declares d as dict * and then initializes it in single line.
Your assumption is wrong, the object exists starting from the = sign that starts the initialization. E.g in a initializer you are well allowed to use the address of the object that you are initializing.
Here, in addition, no access to the object itself is needed, sizeof only uses the type in this case.