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

后端 未结 3 1827
抹茶落季
抹茶落季 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: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], " \r\n", id);
    i += sprintf(&buffer[i], "");
    

    or:

    int i = strlen(buffer);
    i += sprintf(&buffer[i], " \r\n", id);
    strcat(&buffer[i], "");
    

    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++.

提交回复
热议问题