Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd behavior of function with variable number of parameters in C

I have the following C function with a variable number of arguments, which is supposed to search the char* word through a hashtable and write true or false in a file which, if specified, is the second parameter; otherwise, it is stdout.

It works fine if I specify the name of the file, the problem is when I don't (e.g. find("foo")). In this case it writes the result in a file named foo instead of stdout.

What is the cause?

void find(char* word, ...)
{
va_list list;
char *fname = NULL;
va_start(list, word);
FILE* f;
fname = strdup(va_arg(list, char*));
va_end(list);
if (<condition>)    // condition suited for the case in which the file name is received 
    f = fopen(fname, "a");
else
    f = stdout;
if (member(word))
    fprintf(f, "True\n");
else
    fprintf(f, "False\n");
}

In place of <condition> I've tried fname != NULL and strlen(fname) > 0 but those don't apply and it keeps seeing fname as word when fname is not specified.

Thank you very much for any help you can provide.

like image 287
thehousedude Avatar asked Feb 24 '13 09:02

thehousedude


Video Answer


1 Answers

From va_*'s man page:

If there is no next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), random errors will occur.

If you want to use a variable parameter list, you need to devise some sort of terminator for the list (e.g., always add a dummy NULL argument):

find (word, NULL);
find (word, filename, NULL);

or supply the number of parameter as parameter:

find (1, word);
find (2, word, filename);
like image 131
LSerni Avatar answered Nov 15 '22 01:11

LSerni