I\'m porting some very old (> 10y) C code to modern Linuxes. I\'m getting segmentation faults within a custom-written vsnprintf() wrapper (apparently its task is to detect d
This is the correct way to use snprintf and vsnprintf on every operating system except SunOS 4 (which has been obsolete for 20 years), so your problem is somewhere else.
I'll make a pure guess and say that I'm almost certain that your problem is that you're passing the va_list ap into vsnprintf which consumes it and then you expect it to be reset on the next call. This is incorrect and has stopped working in gcc many years ago (because it only worked on certain architectures).
Change:
n = vsnprintf(p, size, fmt, ap);
To:
va_list apc;
va_copy(apc, ap);
n = vsnprintf(p, size, fmt, apc);
va_end(apc);
And see if that helps.
Here's a simple test to see what's going on:
#include
#include
#include
void
foo(const char *fmt, va_list ap)
{
#ifdef BAD
vprintf(fmt, ap);
#else
va_list apc;
va_copy(apc, ap);
vprintf(fmt, apc);
va_end(apc);
#endif
vprintf(fmt, ap);
}
void
bar(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
foo(fmt, ap);
va_end(ap);
}
int
main(int argc, char **argv)
{
bar("foo %s\n", "bar");
return 0;
}
When run I get this:
$ cc -o foo foo.c && ./foo
foo bar
foo bar
$ cc -DBAD -o foo foo.c && ./foo
foo bar
foo ����