What is the difference between vsnprintf and vsprintf_s?

I am currently writing code to process strings. As part of this, I use vsnprintf().

However, the compiler blinks below the error message:

dont_call: vsnprintf(). Invokation of a potentially dangerous function
    that could introduce a vulnerability. remediation:
    Recommendation: Use vsprintf_s() instead!

Results with are vsprintf_s()not expected.

What is the difference between vsnprintf()and vsprintf_s()?

+4
source share
2 answers

The solution is to always add

#define _CRT_SECURE_NO_WARNINGS

as the first line of code when compiling with Visual Studio. Or maybe the second line, if you are writing cross-platform code, and the first line is something like #ifdef _WIN32, for example

#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#endif

This will disable warnings that Microsoft has "deprecated" features required by the C standard.

+5

vsnprintf() - , , , .

Microsoft , , , , : , , %n, .

, , . . , , , undefined. , , , .

2 vsnprintf(), K, , , :

int vsprintf_s(char * restrict s, rsize_t n,
          const char * restrict format,
          va_list arg);

int vsnprintf_s(char * restrict s, rsize_t n,
          const char * restrict format,
          va_list arg);

- snprintf -:

  • %n.
  • n 0.
  • s , snprintf() n 0.
  • vsprintf_s vsnprintf_s, , n-1: , 0 , , vsnprintf, vsnprintf_s do.

, snprintf(), :

/* allocate a string formated according to `format` */
int vasprintf(char **strp, const char *format, va_list ap) {
    va_list arg;
    int ret;

    if (!strp) {
        errno = EINVAL;
        return -1;
    }

    va_copy(arg, ap);
    ret = vsnprintf(NULL, 0, format, arg);
    va_end(arg);

    *strp = NULL;
    if (ret < 0 || (*strp = malloc(ret + 1)) == NULL) {
        return -1;
    }

    return vsnprintf(*strp, ret + 1, format, ap);
}

vnsprintf vsprintf_s, vsprintf_s : . vsnprintf_s , NULL, .

: vsnprintf vsnprintf_s 1 NULL, 0:

/* allocate a string formated according to `format` */
int vasprintf(char **strp, const char *format, va_list ap) {
    char buf[1];
    va_list arg;
    int ret;

    if (!strp) {
        errno = EINVAL;
        return -1;
    }

    va_copy(arg, ap);
    ret = vsnprintf_s(buf, 1, format, arg);
    va_end(arg);

    *strp = NULL;
    if (ret < 0 || (*strp = malloc(ret + 1)) == NULL) {
        return -1;
    }

    return vsnprintf_s(*strp, ret + 1, format, ap);
}

, : Visual Studio , :

#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#endif

.

, , . gcc clang -Wall , . Visual Studio /W4.

+2

Source: https://habr.com/ru/post/1686622/


All Articles