Home > OS >  Problem while using sprintf in C and getting warning
Problem while using sprintf in C and getting warning

Time:10-23

Whenever I am trying to use sprintf() while coding in C, I am getting a warning saying :

"warning: ‘%s’ directive writing up to 49 bytes into a region of size 39 [-Wformat-overflow=]"

It is also producing a note saying :

"note: ‘sprintf’ output between 13 and 62 bytes into a destination of size 50 62 | sprintf(msg,"fopen-ing "%s"",data_file);"

Below I am giving some part of my code, mainly where I am getting this warning.

char data_file[50]; // Global

void initialize_from_data_file()
{
    FILE *fpS;
    if((fpS = fopen(data_file,"r")) == NULL)
    {
        char msg[50];
        sprintf(msg,"fopen-ing \"%s\"",data_file);
        perror(msg);
        exit(1);
    }
    ...
}

As I am newly using this language so unable to understand how to remove this warning.

CodePudding user response:

It's warning you that the destination buffer for sprintf might not be big enough to hold the string you want to put in it. If data_file is more than around 40 characters long, sprintf will write past the end of the array msg.

Make msg big enough to hold the string that would go in it:

char msg[70];

There's another problem however. Since you call sprintf right before calling perror, the latter will reporting the error status of the sprintf call, not the fopen call.

So don't use sprintf at all in this case and use strerror to get the error string:

fprintf(stderr,"fopen-ing \"%s\": %s",data_file,strerror(errno));
  • Related