What is a Singleton pointer in C?

I have code like this (this is not production code. Just a code example)

char *inbuf = NULL; inbuf = buf; //buf is some other valid buffer of size 100. func(&inbuf); ..... void func(char **p) { ... (*p)++; ... } 

The Coverity Tool says that "Accepting an address with & inbuf gives a singleton." I have heard the term singleton with respect to C ++. But what does a single point pointer mean in terms of C?

+7
source share
2 answers

What does a single pointer mean in terms of C?

In this case, I think Coverity refers to the difference between a char * array and a pointer to a single char* created using the address of this array.

Coverity warns you that by passing the address of the first buf element to func , you are making it difficult for yourself to safely write to this array because you cannot easily determine its size.

It's hard to be sure without seeing all of your code, but assuming buf is an array that you specified somewhere in your top-level function, and then using sizeof on buf from that function, you get the size of the array.

However, when you pass the buf address to func on the line

 func(&inbuf); 

... func just gets a pointer to the first element of this array. From func you can no longer use sizeof to determine the size of the array — it simply returns the size of the pointer — and you cannot safely write to this pointer without any implicit understanding of how much space is in the array.

This makes fragile code, and therefore this is bad practice.

(None of this is related to the Singleton Pattern )

+8
source

Coverage analysis displays a defect in 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 an error pattern, often because a function expects a pointer to a buffer, but you pass it a pointer to a single value. Type systems in C / C ++ do not distinguish between "pointer to one object" and "pointer to an array of objects".

0
source

All Articles