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. sizeof
is based on compile-time information,1 so it doesn't matter that ret
has only just been declared.
This idiom is the preferred way of using malloc
. If you were to use be_node *ret = malloc(sizeof(be_node))
, then consider what would happen if you change the type of ret
at a later date. If you forget to replace both uses of "be_node
", then you will have introduced a subtle bug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With