snprintf for Windows MSVC

Post tutorials on how to do certain tasks within game or engine code here.
Post Reply
Baker
Posts: 3666
Joined: Tue Mar 14, 2006 5:15 am

snprintf for Windows MSVC

Post by Baker »

For sure, MSVC6 doesn't have an snprintf equivalent which can be used to avoid string buffer overflows

_snprintf on MSVC6 doesn't null terminate.

The following functions are from the ezQuake source code and I've thrown in ezQuake's version of va (...)

Code: Select all

// Added by VVD 
int qsnprintf(char *buffer, size_t count, char const *format, ...)
{
	int ret;
	va_list argptr;
	if (!count) return 0;
	va_start(argptr, format);
	ret = _vsnprintf(buffer, count, format, argptr);
	buffer[count - 1] = 0;
	va_end(argptr);
	return ret;
}
int qvsnprintf(char *buffer, size_t count, const char *format, va_list argptr)
{
	int ret;
	if (!count) return 0;
	ret = _vsnprintf(buffer, count, format, argptr);
	buffer[count - 1] = 0;
	return ret;
}


#define snprintf qsnprintf		// vc++ snprintf and vsnprintf are non-standard and not compatible with C99.
#define vsnprintf qvsnprintf	// vc++ snprintf and vsnprintf are non-standard and not compatible with C99.
#define strcasecmp stricmp		// MSVC has a different name for several standard functions
#define strncasecmp strnicmp	// MSVC has a different name for several standard functions


//does a varargs printf into a temp buffer, so I don't need to have varargs versions of all text functions.
char *va (char *format, ...)
{
	va_list argptr;
	static char string[32][2048];
	static int idx = 0;

	idx++;
	if (idx == 32)
		idx = 0;

	va_start (argptr, format);
	vsnprintf (string[idx], sizeof(string[idx]), format, argptr);
	va_end (argptr);

	return string[idx];
}
The night is young. How else can I annoy the world before sunsrise? 8) Inquisitive minds want to know ! And if they don't -- well like that ever has stopped me before ..
szo
Posts: 132
Joined: Mon Dec 06, 2010 4:42 pm

bad return value

Post by szo »

This is incomplete for people who'd expect c99-compliant behavior.. You moust do

Code: Select all

if (ret < 0) ret = (int)size;
The count == 0 case also doesn't conform to c99, either. See the standarts, or at least recent unix (linux) man pages.
Baker
Posts: 3666
Joined: Tue Mar 14, 2006 5:15 am

Re: bad return value

Post by Baker »

szo wrote:This is incomplete for people who'd expect c99-compliant behavior.. You moust do

Code: Select all

if (ret < 0) ret = (int)size;
The count == 0 case also doesn't conform to c99, either. See the standarts, or at least recent unix (linux) man pages.
Thanks for headsup. Yes I do want C99-complaint behavior.
The night is young. How else can I annoy the world before sunsrise? 8) Inquisitive minds want to know ! And if they don't -- well like that ever has stopped me before ..
Post Reply