Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a Singleton pointer in C?

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?

like image 693
Jay Avatar asked Jun 07 '12 15:06

Jay


1 Answers

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)

like image 60
razlebe Avatar answered Oct 10 '22 16:10

razlebe