Is it correct to use the same array as input and output in sprintf?

7

I found the following code:

char query[255];
sprintf(query, "SELECT NOMBRE, ");
switch (tipo)
{
    case TIPO_1:
        sprintf(query, "%s ID", query);
        break;
    case TIPO_2:
        sprintf(query, "%s APELLIDO", query);
        break;
} 

And what worries me is the use of query making the role of both read and write parameter of sprintf .
The code works well and does what is expected of our compiler and our tests.

Assuming the size of the array is not exceeded. And that whenever you use query as a reading parameter, it is the first parameter after formatting and the format begins with "% s".
Is it a correct use? Or is there a situation where it could go wrong?

    
asked by Jose Antonio Dura Olmos 13.01.2016 в 16:02
source

2 answers

4

If we review what the function documentation says in GNU :

  

The behavior of this function is undefined if copying takes place between objects that overlap-for example, if it is also given as an argument to be printed under the control of the '% s' conversion. See Copying and Concatenation.

In your case you are overlapping the input buffer with the output buffer, then the result, as indicated in the first comment, depends solely on the implementation you use at all times.

In any case, although it works for specific situations, it is something to avoid given the randomness of the result. There are much more robust solutions that only require the use of an additional variable.

    
answered by 13.01.2016 / 17:24
source
1

With respect to the functions of the standard librarian of C as sprintf , C ++ refers to the standard of C, with some qualifications (but none for sprintf ). For its part, the C standard (in §7.19.6.6 in C99, §7.21.6.6 in C11) says that if a copy occurs between overlapping objects, indefinite behavior occurs.

According to both standards, as soon as indefinite behavior occurs, the result can be unpredictable.

    
answered by 13.01.2016 в 20:04