Is sprintf(buffer, “%s […]”, buffer, […]) safe?

后端 未结 3 1818
抹茶落季
抹茶落季 2020-12-03 02:56

I saw use of this pattern to concatenate onto a string in some code I was working on:

sprintf(buffer, \"%s \\r\\n\",         


        
相关标签:
3条回答
  • 2020-12-03 03:46

    From the glibc sprintf() documentation:

    The behavior of this function is undefined if copying takes place between objects that overlap—for example, if s is also given as an argument to be printed under control of the ‘%s’ conversion.

    It may be safe in a particular implementation; but you could not count on it being portable.

    I'm not sure that your proposal would be safe in all cases either. You could still be overlapping buffers. It's late and my wife is buggin me but I think that you could still have the case where you want to use the original string again in the concatenated string and are overwriting the null character and so the sprintf implementation might not know where the re-used string ends.

    You might just want to stick with a snprint() to a temp buffer, then strncat() it onto the original buffer.

    0 讨论(0)
  • 2020-12-03 03:47

    If you want to concatenate formatted text to the end of a buffer using printf(), I'd recommend you use an integer to keep track of the end position.

    int i = strlen(buffer);
    i += sprintf(&buffer[i], " <input type='file' name='%s' />\r\n", id);
    i += sprintf(&buffer[i], "</td>");
    

    or:

    int i = strlen(buffer);
    i += sprintf(&buffer[i], " <input type='file' name='%s' />\r\n", id);
    strcat(&buffer[i], "</td>");
    

    And before people go berserk downvoting this ("This isn't safe! You can overrun the buffer!"), I'm just addressing a reasonable way to build a formatted string in C/C++.

    0 讨论(0)
  • 2020-12-03 03:55

    In this specific case, it is going to work because the string in buffer will be the first thing that is going to enter in buffer (again, useless), so you should use strcat() instead to get the [almost] same effect.

    But, if you are trying to combine strcat() with the formating possibilities of sprintf(), you may try this:

    sprintf(&buffer[strlen(buffer)], " <input type='file' name='%s' />\r\n", id);
    0 讨论(0)
提交回复
热议问题