5

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.

1
  • 1
    varargs are not supposed be used this way. You are better off using void find(char* word, char* filename) and checking if filename is NULL and if so write to stdout. Also don't forget to close the file, you opened, if you did open a file. Commented Feb 24, 2013 at 9:34

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

OK, thanks for remembering me. It works with NULL at the end of the list. Initially I thought that NULL (or other behavior) was somehow implied for arguments that weren't received, but it doesn't know by itself when the list ends.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.