Reputation: 5762
I have written a function to help me debug a project:
static void outputDebug(unsigned uintLineNo, const char* cpszFormat, ...) {
char szPrefix[80], szOut[256];
va_list ap;
va_start(ap, cpszFormat);
sprintf_s(szPrefix, sizeof(szPrefix), "%s %s %05ld %s\n"
, __DATE__, __TIME__, uintLineNo, cpszFormat);
vsprintf_s(szOut, sizeof(szOut), "%s", szPrefix, ap);
va_end(ap);
OutputDebugString(szOut);
}
An example of this function:
outputDebug(__LINE__, "AdapterInit(%s)", "Test");
Everything after the format string AdapterInit(%s)
is optional, I've single stepped the function and it constructs the szPrefix
without problems, as an example this would contain something like; Apr 18 2018 07:33:07 01492 Adapter(%s)
The next line vsprintf
results in a exception:
Unhandled exception at 0x0781e9ee (msvcr90d.dll) in ....
I can't see what I've done wrong, how can I resolve this?
[Edit] The problem was in the line starting vsprintf
, removing the unnecessary %s
resolved the problem.
Working solution:
static void outputDebug(unsigned uintLineNo, const char* cpszFormat, ...) {
char szPrefix[80], szOut[256];
va_list ap;
va_start(ap, cpszFormat);
sprintf_s(szPrefix, sizeof(szPrefix), "%s %s %05ld %s\n"
, __DATE__, __TIME__, uintLineNo, cpszFormat);
vsprintf_s(szOut, sizeof(szOut), szPrefix, ap);
va_end(ap);
OutputDebugString(szOut);
}
Upvotes: 0
Views: 192
Reputation: 170203
If I gather correctly, you construct szPrefix
as the new format string (by interpolating cpszFormat
into it, adding a prefix). So the call to vsprintf_s
should use that, instead of %s
. I.e.
vsprintf_s(szOut, sizeof(szOut), szPrefix, ap);
Your chosen size for szPrefix
(that 80) is also fairly optimistic. May be worth increasing it a notch or two.
Upvotes: 1