What is the behaviour of this C code snippet?
Recently I saw following piece code:
if ((rgb = (fp16 *)malloc(width*height*sizeof (*rgb)*3)) == NULL)
rgb is declared as a pointer of some class type. In the above code, malloc() is taking arguments which is width*height*sizeof(*rgb)
So it is some kind of self referential initialization(If i may call it by giving this name!) i.e. belore rgb pointer is allocated by malloc, it is dereferencing it in call 开发者_Python百科to malloc.
In this particular code, i saw that the pointer rgb is not initialized to NULL or anything.
What would be the behaviour of such code.
Normal functioning or
Crash due to null pointer dereference, or a
Garage pointer dereference
thanks,
-AD.
sizeof
does not evaluate its operand, so in this case sizeof(*rgb)
will return the size of rgb
's type, which I assume is fp16 *
.
Completely valid C code.
If it did evaluate it and the pointer was just some declared pointer with no initialized value, then you would get undefined behavior.
It's not actually dereferencing the pointer, sizeof(*rgb)
does a compile-time determination of the size of the type pointed to by rgb
. The machine code generated by that line will use a literal number in place of the sizeof(*rgb)
term.
sizeof
doesn't evaluate its argument. It only computes its size. So you don't get the undefined behaviour associated to uninitialized pointer dereferentiation.
Under normal circumstances, the if block would not happen when malloc succeeds. If malloc fails, the block will be executed.
Quoted:
i saw that the pointer rgb is not initialized to NULL or anything.
if rgb is initialized to NULL, then it will go through that if
condition.
That is code line is fine.
精彩评论