2

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.

5
  • msg is too small to accommodate the result of sprintf. Commented Oct 22, 2021 at 17:24
  • msg is a buffer cointaing space for 50 characters and you're sending (potentially) 50 characters (from data_file) + 12 extra chars in the format string. The compiler is warning you that this could overflow. You should alloc more space in the msg buffer. Commented Oct 22, 2021 at 17:24
  • Do you understand what sprintf does? Can you estimate how many characters it's going to produce? Can you verify if that output fits the destination array? Commented Oct 22, 2021 at 17:24
  • The messages are pretty clear. You want to produce a string and store it in a space that is not large enough for it. Commented Oct 22, 2021 at 17:28
  • Thank you. Now I understood properly. Commented Oct 22, 2021 at 17:30

1 Answer 1

8

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.