Search code examples
cstringbuffer-overflow

How can I use strncat without buffer overflow concerns?


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, "String 2", sizeof(buff));

strncat(buff, "String 3", sizeof(buff));

Instead of sizeof(buff), I want to say something buff - xxx. I want to make sure I never override the buffer


Solution

  • 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);