What does malloc do in this situation?

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

A line of code 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 sizeof (* ret) will return if it has just been declared?

+4
source share
4 answers

This is no different than any other use of sizeof ; he will evaluate the size of his operand. sizeof based on compile-time information, 1 so it doesn’t matter that ret just been declared.

This idiom is the preferred way to use malloc . If you used be_node *ret = malloc(sizeof(be_node)) , then think about what happens if you change the ret type to a later date. If you forget to replace both use cases with " be_node ", you will be_node subtle bug.


<Sub> 1. Except with variable length arrays.
+11
source

sizeof(*ret) resolved by the compiler and looks only at type *ret , not its contents. In this case, this is the size of be_node. It is also resolved at compile time, and not at run time, so it does not "return" as such, it is simply replaced by a constant.

The compiler will select sizeof(*ret) and replace it with a constant number whose size is be_node in bytes.

+2
source

Is it a shortcut or whatever you can name.

You can write

 be_node *ret = malloc(sizeof(be_node)); 

or

 be_node *ret = malloc(sizeof(*ret)); 

In the first case, you basically say "allocate a block of memory large enough to store be_node". In the second case, you say "allocate a block of memory large enough to hold all the return points." Which one do you prefer is basically a matter of preference.

+1
source

sizeof works with both data types and actual variables. In your case, you call it with a variable as a parameter. By the time you call the sizeof variable, it is DECLARED (not initialized, but declared), so it will know the type var and will be able to calculate the memory requirements in bytes that will be returned and used by malloc.

+1
source

All Articles