Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

395
Vistas
Giving snprintf() a too large size when output is small enough

Does this code cause undefined behaviour? Because the buffer is only 128 byte long but i tell snprintf() that it is longer. However, the resulting string is shorter than 128 byte.

#include <stdio.h>

int main(void)
{
  char buffer[128];
  snprintf(buffer,294201,"%s","ABC");
  puts(buffer);
  return 0;
}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

C 2018 7.21.6.5 2 says:

The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by argument s) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array.

Note this does not say snprintf is passed an array of n or more characters. So snprintf is not given any license to assume it may write to s[n-1] unless the fprintf that it is equivalent to would write n characters (including the terminating null character).

Looking at this another way, suppose we define an array buffer of 294,201 characters, fill it with data, and call snprintf(buffer,294201,"%s","ABC");. Would we expect nothing beyond the first four characters to change? If some other byte in the buffer changed, then this snprintf call would not be “equivalent to fprintf, except that the output is written into an array…” I would deem it a violation of this specification if it changed anything further in the buffer.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda