I have some code which is like this (This is not production code. Just a sample code)
char *inbuf = NULL;
inbuf = buf; //buf is some other valid buffer of size 100.
func(&inbuf);
.....
void func(char **p)
{
...
(*p)++;
...
}
Coverity Tool says that "Taking address with &inbuf yields a singleton". I have heard the term singleton with respect to C++. But, what does a singleton pointer mean in terms of C?
What does a singleton pointer mean in terms of C?
In this case I think Coverity is referring to the difference between an array of char* and a pointer to a single char*
created by taking the address of that array.
Coverity is warning you that by passing the address of the first element of buf
to func
, you're making it more difficult for yourself to safely write to that array because you can't easily determine its size.
It's difficult to be sure without seeing all of your code, but assuming buf
is an array you've declared somewhere in your top-level function then using the sizeof
operator on buf
from that function will yield the size of the array.
However, when you pass the address of buf
to func
at the line
func(&inbuf);
...func
merely receives a pointer to the first element of that array. From func
you can no longer use sizeof
to determine the size of the array - it will just return the size of the pointer - and so you can't safely write to that pointer without some implicit understanding of how much space the array contains.
This makes for fragile code, and hence is poor practice.
(None of this is anything to do with the Singleton Pattern)
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