How can I use strncat without buffer overflow concerns?

前端 未结 5 613
野趣味
野趣味 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:14

    Hogan has answered the question sufficently; however, if you are worried about buffer overflows in strcat(...) you should equally be worried about buffer overflows in all the other string functions.

    Use strnlen(...) and strncpy(...) to really make sure you stay within your buffer. If you don't have a strnlen(...) function, write it.

    0 讨论(0)
  • 2020-12-03 06:29

    This is the best way to do it. sizeof() just gives you size of the pointer to the data if you don't allocate it locally (you did allocate locally in this case but better to do it this way and it will work if the code is re-factored).

    #define MAXBUFFSIZE 64
    
    char buff[MAXBUFFSIZE];
    
    buff[0] = 0;  // or some string
    
    strncat(buff, "String x",MAXBUFFSIZE - strlen(buff) - 1);
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-03 06:34

    Why not use snprintf? Unlike strncat it expects the size of the buffer, but more importantly, there's no hidden O(n).

    Strcat needs to find the null-terminator on each string it concatenates, and each time run through the whole buffer to find the end. Each time the string gets longer, strcat slows down. Sprintf, on the other hand can keep track of the end. you'll find that

    snprintf(buf, sizeof buf, "%s%s%s", "String1", "String2", "String3");
    

    Is frequently a faster, and more readable soluton.

    0 讨论(0)
  • 2020-12-03 06:39

    Take into consideration the size of the existing string and the null terminator

    #define BUFFER_SIZE 64
    char buff[BUFFER_SIZE];
    
    //Use strncpy
    strncpy(buff, "String 1", BUFFER_SIZE - 1);
    buff[BUFFER_SIZE - 1] = '\0';
    
    strncat(buff, "String 2", BUFFER_SIZE - strlen(buff) - 1);
    
    strncat(buff, "String 3", BUFFER_SIZE - strlen(buff) - 1);
    
    0 讨论(0)
提交回复
热议问题