In the below code the fputs(…) throws an assert when running on Windows Server 2008. I don’t have this problem on a Vista or XP machine. I’m at a loss as to what is causing it?
The assert is: Stream != NULL
It seems to be random too, as sometimes it seems to succeed… as the log files get created.
Can anybody help?
void DLog::Log(const char *fmt, ...)
{
va_list varptr;
va_start(varptr, fmt);
int n = ::_vscprintf(fmt, varptr);
char *buf = new char[n + 1];
::vsprintf(buf, fmt, varptr);
va_end(varptr);
if (!m_filename.empty())
{
FILE *f = fopen(m_filename.c_str(), "at");
if (f != NULL)
{
fputs(buf, f);
fputs("\n", f);
fclose(f);
}
else
::MessageBox(0,"Error at fputs in Log","Error",0);
}
delete [] buf;
}
Is it the second
fputsthat’s asserting? Is it possible yourvsprintfis overrunning the end of your buffer? Your format string and actual varargs may not match correctly.Your question is tagged C++ and there are definitely better ways to do this in that language.
At least consider using
std::ofstreamto do your writing instead of the old CFILE*API. But better still is to forget the varargs function completely and using an insertion operator like the C++ standard streams. Then you get type safety and remove the need for easily mis-passed varargs parameters.