izac89
izac89

Reputation: 3930

Building a string from a given format and unknown number of arguments

I have the following code in order to build a string from a given argument list:

void MyLog
(
    const char * formatPtr,
    ...
)
{
    va_list args;

    char buffer[BUFFER_LENGTH];

    /* Initializing the buffer */
    memset(buffer, NULL, BUFFER_LENGTH);

    /* Formatting the arguments */
    va_start(args, formatPtr);
    vsprintf(buffer, formatPtr, args);
    va_end(args);

    /* Print arguments as a formatted string */
    printf(buffer);

}

This code is prone to buffer overflow if the arguments length exceeds BUFFER_LENGTH. Now, I have a constraint which allows me to use only static allocations, as in buffer[BUFFER_LENGTH]. How can I modify this code in order to provide a correct solution for providing a null terminated string that contains the formatted arguments list, in which if the formatted arguments string length exceeded BUFFER_LENGTH then the resulting string will contain the arguments until the last argument which fits to BUFFER_LENGTH maximal length.

A proper solution will be to use char* result = getFormattedString(formatPtr, args) but I am not aware of such existing function in C libraries.

Upvotes: 0

Views: 117

Answers (1)

2501
2501

Reputation: 25753

The usage of the function sprintf in your example is not correct. You need the function vsprintf.

The function vsnprintf is the function you're looking for, as it has an additional parameter that determines the size of the buffer.

Upvotes: 3

Related Questions