Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading