• Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Precios
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

110
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;
}
11 months 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.

11 months 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 empleo Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.