Search code examples
cfxcop

Removing C6054 error with scanf functions


I am using Code Analysis (aka FxCop) on VS2012 and I have a few functions of the form

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

These always throw warning C6054: String 'label' might not be zero-terminated. I understand why this happens, since they can't use SAL annotations to indicate the output from fscanf will be null-terminated, but the fact remains.

Is there a way to get rid of this warning (without disabling the relevant Code Analysis check wholesale)? Or is it something I just have to live with when using scanf?


Solution

  • If scanf fails the buffer remains uninitialized. User may enter more than 32 characters writing out-of-bounds. In either case the buffer will not be null terminated.

    First initialize the buffer correctly:

    char label[32] = { 0 };
    

    then make sure you read at most 31 characters and check the return value of the call:

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