Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

88
Views
Problem while using sprintf in C and getting warning

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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));
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!