How can I use strncat without buffer overflow concerns?

前端 未结 5 627
野趣味
野趣味 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: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);
    

提交回复
热议问题