10

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?

Jay
  • 24,173
  • 25
  • 93
  • 141

2 Answers2

10

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)

Community
  • 1
  • 1
razlebe
  • 7,134
  • 6
  • 42
  • 57
1

The Coverity analysis is flagging a defect of the following pattern:

typeA var;        // declare a variable to some type
func(&var)        // call a function passing the address of var

func(typeA *var) {
      ...
      var++;      // inside the function do pointer arithmetic on var

This is a bug pattern, frequently, because the function expects a pointer to a buffer, but you're passing it a pointer to a singleton value. The type systems in C/C++ do not distinguish between "pointer to one object" and "pointer to array of objects".

Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133
  • 2
    Shouldn't be the first line: "typeA var[x]; // declare an array variable of some type"? – pmod Jun 08 '12 at 05:42
  • no, the whole point is what makes it a bug is you would be passing a pointer to a singleton object, not an array. – Asya Kamsky Jun 08 '12 at 05:46