Either I'm getting dumber or C++ is getting harder !
I cannot figure out why the same function performs differently in debug and release configurations (VS 2005 Std Edition, C++). Take this simple console application.
Code:
#include <string>
#include <cstdlib>
#include <cstdio>
#include <iostream>
using namespace std;
#include <cstdarg> // needed to use ellipses
void xWrite(char* logline, ...)
{
va_list argList;
char cbuffer[1024];
va_start(argList, logline);
// int n = vsnprintf_s(cbuffer, 1024, strlen(cbuffer), logline, argList);
int n = _vsnprintf_s(cbuffer, 1024, strlen(cbuffer), logline, argList);
va_end(argList);
cout << cbuffer << endl;
cout << "n = " << n << endl; // 43 in debug mode, -1 in release mode
}
int main()
{
xWrite("Gimme %d and I'll take %0.2f to get to %s.", 3, 4.56, "seven");
return 0;
}
When run in Release configuration:
G
n = -1
When run in Debug configuration:
Gimme 3 and I'll take 4.56 to get to seven.
n = 43
I don't know how you folks feel about this kind of thing, but I find it rather disheartening. And I find myself loosing confidence in the Microsoft compiler.
Microsoft provides the usual confusing harangue regarding the function, vsnprintf_s.
Re: Either I'm getting dumber or C++ is getting harder !
Originally Posted by Mike Pliam
I don't know how you folks feel about this kind of thing, but I find it rather disheartening. And I find myself loosing confidence in the Microsoft compiler.
It isn't the compiler, it's your code.
Code:
char cbuffer[1024];
//...
strlen(cbuffer);
What does strlen() return? Please don't say "1024".
Re: Either I'm getting dumber or C++ is getting harder !
You're asking strlen to determine the length of an uninitialized c-string. There's no telling what number it may spit out. You're probably being saved in the debug build by some of the extra bounds checking stuff that the compiler does automagically. In the optimized release build, none of that exists.
Re: Either I'm getting dumber or C++ is getting harder !
It's an _s function. There's some rather silly redundancy in several of those.
My guess is that Microsoft thought some people would confuse "bytes" with "character count" if they didn't give them explicitly different fields. For chars it's the same; for wchar_ts, not so much.
Honestly I don't ever use the _s functions myself. I generally think the better solution is to just use C++ methods which sidestep the safety issues entirely.
Bookmarks