What does this line of C code do?
be_node *ret = malloc(sizeof(*ret));
The definition of be_node can be found in this file: http://funzix.git.sourceforge.net/git/gitweb.cgi?p=funzix/funzix;a=blob_plain;f=bencode/bencode.h;hb=HEAD
The line of code above was found in this file: http://funzix.git.sourceforge.net/git/gitweb.cgi?p=funzix/funzix;a=blob_plain;f=bencode/bencode.c;hb=HEAD
I don’t understand what the sizeof(*ret) would return if it has only just been declared?
It’s no different to any other use of
sizeof; it will evaluate the size of its operand.sizeofis based on compile-time information,1 so it doesn’t matter thatrethas only just been declared.This idiom is the preferred way of using
malloc. If you were to usebe_node *ret = malloc(sizeof(be_node)), then consider what would happen if you change the type ofretat a later date. If you forget to replace both uses of “be_node“, then you will have introduced a subtle bug.1. Except in the case of variable-length arrays.