4

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?

Wasabi
  • 2,879
  • 3
  • 26
  • 48
  • @user3121023 I'm compiling now with that test (it takes a while), but even if that works, it isn't a really extensible solution, especially if there's a case where `label` is dynamically allocated. – Wasabi Mar 30 '16 at 20:58

1 Answers1

3

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
}
2501
  • 25,460
  • 4
  • 47
  • 87