WVUThorns: sprintf use violates standard

Issue #2749 resolved
Erik Schnetter created an issue

I see these warnings when building WVUThorns:

/Users/eschnett/Cactus/arrangements/WVUThorns_Diagnostics/particle_tracerET/src/file_output_routines.C: In function 'void particle_tracerET_file_output_ascii(cGH*)':
/Users/eschnett/Cactus/arrangements/WVUThorns_Diagnostics/particle_tracerET/src/file_output_routines.C:143:14: warning: 'sprintf' argument 3 overlaps destination object 'buffer' [-Wrestrict]
  143 |       sprintf(buffer, "%s %e %e %e %e", buffer, particle_u4U0[which_particle], particle_u4U1[which_particle], particle_u4U2[which_particle], particle_u4U3[which_particle]);
      |       ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/eschnett/Cactus/arrangements/WVUThorns_Diagnostics/particle_tracerET/src/file_output_routines.C:154:14: warning: 'sprintf' argument 3 overlaps destination object 'buffer' [-Wrestrict]
  154 |       sprintf(buffer, "%s %e %e %e %e", buffer, particle_u4D0[which_particle], particle_u4D1[which_particle], particle_u4D2[which_particle], particle_u4D3[which_particle]);
      |       ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/eschnett/Cactus/arrangements/WVUThorns_Diagnostics/particle_tracerET/src/file_output_routines.C:132:12: warning: 'sprintf' argument 3 overlaps destination object 'buffer' [-Wrestrict]
  132 |     sprintf(buffer, "%s %e %e %e", buffer, particle_position_x[which_particle], particle_position_y[which_particle], particle_position_z[which_particle]);
      |     ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
COMPILING WVUThorns_Diagnostics/particle_tracerET/src/Interpolate_velocities_at_particle_positions.C

The C/C++ standards do not allow writing the buffer to itself (although this is a convenient way to append to a string).

Since this is C++ code I suggest to use std::ostringstream instead.

Comments (4)

  1. Roland Haas

    alternatively (if one needs control over formatting) one can use something like:

    snprintf(buffer+strlen(buffer), sizeof(buffer) - strlen(buffer), "...",  particle_u4U0[which_particle])
    

    where one leaves out the first “buffer” (and its “%s”).

    Alternatively, if this, as I suspect, is written to a file anyway, just use multiple fprintf calls which do use buffering anyway so will typically only write (to a file) in 1k or so chunks. If this is ASCII file IO, then any optimization on the code part is premature anyway since IO (and the binary to ASCII conversion) will be the slow parts anyway (well unless one plasters the code with many many malloc/new/string/osstream object creations that is).

  2. Log in to comment