Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing C6054 error with scanf functions

Tags:

c

fxcop

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?

like image 532
Wasabi Avatar asked Aug 31 '25 00:08

Wasabi


1 Answers

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
}
like image 193
2501 Avatar answered Sep 03 '25 06:09

2501