Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

89
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda