stdarg misuse (C tip #1)

I received some reports in the past about OSSEC segfaulting during startup on 64 bits systems. However, I was never able to reproduce this problem until last week.. I was happily enjoying my “vacation” and playing with ossec on an Ubuntu 64 when I finally got the ugly “2006/12/16 15:26:21 Segmentation fault” during startup. A smile came in my face… I would be able to debug it now :) . After some troubleshooting I finally noticed that I was misusing the stdarg functions. I was never able to reproduce this issue before, because it only happens when there is a configuration problem and ossec tries to print the error message to the log file and to stderr (by default it only writes to the log file).

Basically, what was happening is that I was calling va_start, followed by multiple vfprintf calls. I don’t know exactly why it works on 32 bits systems and not on 64 bits (it should fail everywhere), but the easiest solution was to duplicate the va_list using va_copy. So, just for the record, never do:

va_start(args, msg);
vfprintf(stderr, msg, args);
vfprintf(fp, msg, args);
va_end(args);

If you need to print a formatted string multiple times, just do a vsnprintf, followed by fprintf’s or use va_copy to duplicate the va_list:

va_start(args, msg);
va_copy(args2, args);
vfprintf(stderr, msg, args);
vfprintf(fp, msg, args);
va_end(args);

It may sound like an obvious advice, but it may be useful to someone…

This entry was posted in c, programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>