tags:

views:

22

answers:

1

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;
}
+1  A: 

Is it the second fputs that's asserting? Is it possible your vsprintf is 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::ofstream to do your writing instead of the old C FILE* 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.

Mark B
I like your idea, I'll have a look into that!
Tony