0
votes

From what I have read, this function should work, but for the life of me, I cannot figure out why it isn't.

I override the invalid parameter handler so I can continue running if an invalid parameter is passed (such as a buffer that is too small). asprintf_s macro takes the parameters of a standard sprintf_s, adds the filename and line number, then calls asprintf_s2. It checks to see if the result would have overflowed the buffer, prints the filename and the line of where the overflowed occurred.

Problem: I'm guessing I'm doing something wrong with the variadic parameters as it always returns an overflow.

Output of program below

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <string>
#include <excpt.h>
#include <stdarg.h>


#define asprintf_s(...) asprintf_s2( __FILE__, __LINE__, __VA_ARGS__) 
//#define asprintf_s(...) sprintf_s( __VA_ARGS__ )

inline int asprintf_s2(char *file, int line, char *dest, int sizeOfDest, char *Format, ...)
{
    va_list pArgs;
    va_start(pArgs, Format);

    int sizeOfBuffer = sprintf_s(dest, sizeOfDest, Format, pArgs);

    if (sizeOfBuffer == -1) printf("Buffer Overflow! File: %s LINE: %d\n", file, line );

    va_end(pArgs);

    return sizeOfBuffer;
}


void in_house_invalid_parameter(
    const wchar_t * expression,
    const wchar_t * function,
    const wchar_t * file,
    unsigned int line,
    uintptr_t pReserved
)
{
    // Do nothing on invalid parameter
}



int main()
{
    char temp1[3];
    char temp80[80];
    std::string input;
    int k = -3;

    _set_invalid_parameter_handler(in_house_invalid_parameter);

    strcpy_s(temp1, sizeof(temp1), "XX");
    strcpy_s(temp80, sizeof(temp80), "1");

    printf("Temp1:'%s'\n", temp1);

    k = asprintf_s(temp1, sizeof(temp1), "%s\n", temp80);

    printf("k:%d   temp1:'%s', temp80:'%s'\n", k, temp1, temp80);
    std::getline(std::cin, input);

    return 0;
}
1

1 Answers

1
votes

You just have to use vsprintf or vsprintf_s function

Edit: or vasprintf for your case