lekai
lekai

Reputation: 23

C++, Wrapper function for sprintf_s

after including banned.h (one of microsoft security tools), the compiler gives me an warning that sprintf() function is not safe, and MSDN center gives me a suggestion to use sprintf_s, since my project is cross platform, I wrote a wrapper for sprintf function.

//safe function for sprintf();
void WrapperSprintf( char *buffer, const char *format, ... )
{
#ifdef _WIN32
    sprintf_s(buffer, sizeof(buffer), format,...);
#else
    sprintf(buffer, format, ...);
#endif
}

it gives me an error at line sprintf_s(buffer, sizeof(buffer), format,...);

error C2059: syntax error : '...'

Anyone knows how to write a wrapper function for sprintf_s()?

Thanks a lot.

Upvotes: 2

Views: 6950

Answers (1)

paxdiablo
paxdiablo

Reputation: 882028

The ... doesn't magically translate from the function declaration down to the other calls using those parameters. You have to include the variable arguments stuff and use that to call the next level down.

The steps are basically:

  • include the stdarg header.
  • declare a va_list.
  • call va_start.
  • call one of the v*printf functions.
  • call va_end.

For example, here's a little program that demonstrates how to provide a beast which writes the formatted output to a string, similar to what you seem to be after:

#include <stdio.h>
#include <stdarg.h>

void x (char *buf, char *fmt, ...) {
    va_list va;
    va_start (va, fmt);
    vsprintf (buf, fmt, va);
    va_end (va);
}

int main (void) {
    char buff[100];
    x (buff, "Hello, %s, aged %d", "Pax", 40);
    printf ("%s\n", buff);

    return 0;
}

Me, I tend to ignore Microsoft's suggestions about sprintf being unsafe. It's only unsafe if you don't know what you're doing and that can be said of any tool. If you want to become a good C programmer, you will learn the limitations and foibles of the language.

Including the one where you use sizeof on a char*, expecting it to return the size of the buffer it points to rather than the size of a pointer :-)

But, if you want to be a C++ developer, be a C++ developer. While C and C++ share a lot of commonality, they are not the same language. C++ includes a lot of C stuff primarily so that you can (mostly) take already-written C code and use it in your C++ applications.

In other words, if it's a C++ application, use std::string and std::stringstream(a) rather than char arrays and s*printf calls.

You should be writing your C++ code as if the C bits didn't exist. Otherwise, you're more a C+ programmer than a C++ one :-)


(a) Of course, knowledgeable developers will probably already be steering clear of the verbosity inherent in the stringstream stuff, and be using something like fmtlib (with the conciseness of printf but with the type safety C++ developers have come to appreciate).

Especially since it's being bought into C++20 where it will be part of the base, available to everyone.

Upvotes: 14

Related Questions