使用 scanf 函数消除 C6054 错误

Removing C6054 error with scanf functions

我在 VS2012 上使用代码分析(又名 FxCop),我有一些形式的函数

void ReadTable(FILE *fd)
{
    char label[32];
    /* ... */
    fscanf(fd, "%s", label);
    /* ... */
    if (strcmp(label, "TEST") == 0)
    {
        /* ... */
    }
}

这些总是抛出 warning C6054: String 'label' might not be zero-terminated. 我明白为什么会这样,因为他们不能使用 SAL 注释来指示 fscanf 的输出将以 null 结尾,但事实仍然如此。

有没有办法消除这个警告(不禁用相关的代码分析检查批发)?或者这是我在使用 scanf 时不得不忍受的东西?

如果 scanf 失败,缓冲区将保持未初始化状态。用户可能会输入超过 32 个字符,写越界。在任何一种情况下,缓冲区都不会以空值终止。

首先正确初始化缓冲区:

char label[32] = { 0 };

然后确保您最多读取 31 个字符并检查调用的 return 值:

const int read = fscanf( fd , "%31s" , label );
if( read <= 0 )
{
    //didn't read anything, check feof and ferror
}