【问题标题】:How to mark a particular function argument as a safe format string in Clang?如何在 Clang 中将特定函数参数标记为安全格式字符串?
【发布时间】:2016-10-04 04:29:25
【问题描述】:

我有这样的事情:

static void
my_varargs_internal (const char *prefix, const char *format, va_list args)
{
    printf ("%s: ", prefix);
    vprintf (format, args);
    /* Other more complicated stuff which is why I want this to be a separate function */
    printf ("\n");
}

void
__attribute__ ((format (printf, 1, 2)))
varargs_general (const char *format, ...)
{
    va_list args;
    va_start (args, format);
    my_varargs_internal ("General", format, args);
    va_end (args);
}

void
__attribute__ ((format (printf, 2, 3)))
varargs_specialized (const char *prefix, const char *format, ...)
{
    va_list args;
    va_start (args, format);
    my_varargs_internal (prefix, format, args);
    va_end (args);
}

使用带有-Wformat -Wformat-nonliteral 的Clang 进行编译,我在vprintf 行上收到“格式字符串不是字符串文字”警告。有没有办法将format 参数标记为已检查的格式字符串,因为编译器已经在调用varargs_generalvarargs_specialized 时检查了它?我不能用format 属性来做到这一点,因为它只适用于可变参数函数,而不是带有va_list 参数的函数。

GCC 似乎正确理解了这种情况并且没有发出警告。

【问题讨论】:

    标签: c clang compiler-warnings variadic-functions


    【解决方案1】:

    我能够使用以下方法抑制警告:

    static void
    __attribute__ ((format (printf, 2, 0)))
    my_varargs_internal (const char *prefix, const char *format, va_list args)
    {
        printf ("%s: ", prefix);
        vprintf (format, args);
        /* Other more complicated stuff which is why I want this to be a separate function */
        printf ("\n");
    }
    

    基于Declaring Attributes of Functions:

    对于无法检查参数的函数 (如vprintf),将第三个参数指定为零。

    【讨论】:

      猜你喜欢
      • 2020-05-01
      • 2010-12-21
      • 2018-10-01
      • 2011-09-27
      • 2018-01-07
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多