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

200
Visualizações
Best practice with sprintf?

Here's the situation:

We received code from an outside source that uses sprintf like strcat. Like this:

char buffer[1024];
sprintf(buffer, "Some text.");
sprintf(buffer, "%s%s", buffer, "Some more text");
sprintf(buffer, "%s%s", buffer, "again more text");

Now, this looks weird. We all agree this looks weird. That's not what I'm asking about. We all know that strcat should have been used, and it's more straightforward. I'm asking about the potential issues, aside from looking weird, that this could cause. We're running on RHEL6, and using gcc 4.9.3.

Thanks for your help.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The function is declared like

int sprintf(char * restrict s, const char * restrict format, ...);

pay attention to the type qualifier restrict.

According to the C Standard (7.21.6.6 The sprintf function)

2 The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument s) rather than to a stream. A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.

So these calls

sprintf(buffer, "%s%s", buffer, "Some more text");
sprintf(buffer, "%s%s", buffer, "again more text");

invoke undefined behavior.

Instead the calls could be written like

char buffer[1024];
int offset = 0;

offset = sprintf( buffer + offset, "Some text.");
offset += sprintf( buffer + offset, "%s",  "Some more text");
sprintf( buffer + offset, "%s",  "again more text");

Or

char buffer[1024];
char *p = buffer;

p += sprintf( p, "Some text.");
p += sprintf( p, "%s",  "Some more text");
sprintf( p, "%s",  "again more text");

As for the qualifier restrict then in general words in means (6.7.3 Type qualifiers)

8 An object that is accessed through a restrict-qualified pointer has a special association with that pointer. This association, defined in 6.7.3.1 below, requires that all accesses to that object use, directly or indirectly, the value of that particular pointer

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