Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does malloc do in this situation?

Tags:

c

parsing

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?

like image 323
brnby Avatar asked Dec 07 '22 13:12

brnby


1 Answers

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.


1. Except in the case of variable-length arrays.
like image 162
Oliver Charlesworth Avatar answered Dec 19 '22 08:12

Oliver Charlesworth