GCC syntax check ensure NULL passed as last parameter in function call with variable arguments

StackOverflow https://stackoverflow.com/questions/12962477

  •  08-07-2021
  •  | 
  •  

Domanda

I want to do something similar to how, in GCC, you can do syntax checking on printf-style calls (to make sure that the argument list is actually correct for the call).

I have some functions that take a variable number of parameters. Rather than enforce what parameters are sent, I need to ensure that the last parameter passed is a NULL, regardless of how many parameters are passed-in.

Is there a way to get GCC to do this type of syntax check during compile time?

È stato utile?

Soluzione

You probably want the sentinel function attribute, so declare your function like

void foo(int,double,...) __attribute__((sentinel));

You might consider customizing your GCC with a plugin or a MELT extension to typecheck more precisely your variadic functions. That is, you could extend GCC with your own attributes which would do more precise checks (or simply make additional checks based on the names of your functions).

The ex06/ example of melt-examples is doing a similar check for the jansson library; unfortunately that example is incomplete today October 18th 2012, I am still working on it.

In addition, you could define a variadic macro to call such a function by always adding a NULL e.g. something like:

#define FOO(N,D,...) foo((N),(D),##__V_ARGS__,NULL)

Then by coding FOO(i+3,3.14,"a") you'll get foo((i+3),(3.14),"a",NULL) so you are sure that a NULL is appended.

Altri suggerimenti

Basile Starynkevitch is right, go with a function attribute. There are a ton of other useful function attributes, like being able to tell the compiler "If the caller doesn't check the return value of this function, it's an error."

You may also want to see if splint can check for you, but I don't think so. I think it would have stuck in my memory.

If you haven't read over this page of GCC compiler flags, do that, too. There are a ton of handy checks in there. http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top