c++ converting const char* to char* for long buffer

I have an old function which I can’t change the API

void TraceMsg(const char* fmt, ...)
{
    if (!m_MessageFunctions[TraceLevel]) return;

    char msgBuffer[MAX_LOG_MSG];
    va_list argList;
    va_start(argList, fmt);
    vsnprintf(msgBuffer, MAX_LOG_MSG, fmt, argList);
    va_end(argList);

    m_MessageFunctions[TraceLevel](msgBuffer);
}

MAX_LOG_MSG = 2048

I got into a phase where I would like to allocate more space for the messages for the logger in a dynamic way

I have read this article: https://code-examples.net/en/q/4904e5
and changed my code into:

void TraceMsg(const char* fmt, ...)
{
    if (!m_MessageFunctions[TraceLevel]) return;

    va_list argList;
    va_start(argList, fmt);
    size_t size = vsnprintf(NULL, 0,fmt, argList);
    char* msgBuffer = new char[size];

    vsnprintf(msgBuffer, size, fmt, argList);
    va_end(argList);
    m_MessageFunctions[TraceLevel](msgBuffer);
    delete[] msgBuffer;
}

how ever I get wierd characters like

2022-05-03 12:13:20,939 INFO  Make graph edge Bayer@LSC_1_2 ->Input@DeMux_LSC§§§§н
2022-05-03 12:13:20,939 INFO  Make graph edge Bayer@RGB_IR_2_0 ->0@Mux_X2B_BP§§§§нннннњйн‚€нннннннннннннннннннннннннннннннннннн

Can you please help?

>Solution :

The return value of vsnprintf is

The number of characters that would have been written if n had been
sufficiently large, not counting the terminating null character.

So you need to add 1 to this to make room for the null terminator.

Leave a Reply