How can I use strncat without buffer overflow concerns?

前端 未结 5 623
野趣味
野趣味 2020-12-03 05:33

I have a buffer, I am doing lot of strncat. I want to make sure I never overflow the buffer size.

char buff[64];

strcpy(buff, \"String 1\");

strncat(buff,          


        
5条回答
  •  隐瞒了意图╮
    2020-12-03 06:31

    The way you use the strncat function in your orignal code would actually be appropriate for another function: strlcat (note l instead of n). The strlcat function is not standard, yet it is a popular implementation-provided replacement for strncat. strlcat expects the total size of the entire destination buffer as its last argument.

    Meanwhile, strncat expects the size of the remaining unused portion of the target buffer as its third argument. For this reason, your original code is incorrect.

    I would suggest that instead of doing that horrible abuse of strncpy and making explicit rescans with those strlen calls (both issues present in Joe's answer), you either use an implementation-provided strlcat or implement one yourself (if your implementation provides no strlcat).

    http://en.wikipedia.org/wiki/Strlcpy

提交回复
热议问题