Search code examples
cstringcompiler-constructionconcatenation

strcat vs strncat for string literal


I want to append a string literal to destination. I can use strcat or strncat:

strcat(dest, "values");

Or

strncat(dest, "values", sizeof("values") - 1);

strcat has shorter code, it looks neat.

But I wonder about their runtime performance.

Is strncat slightly faster at runtime because there's no need to locate terminator?

Or maybe compilers could do optimization and so there is no difference?


Solution

  • First, both strcat and strncat loks for the null terminator, the difference is that strncat also check for the size of the copied data, and will copy only n bytes.

    Second, since strcat does not check for the size of the copied data, and copies until it gets to a null terminator, it might (and will!!) cause a buffer overflow, overriding data that is stored in memory after the buffer you copy to.

    Third, your usage of the strncat is not safer, as you limit the copy by the size of the source buffer, not the destination buffer. E.g. to use it correctly you should pass the size of the destination buffer:

    strncat(dest, "values", sizeof(dest) -1 );
    

    Fourth, if the size of the source string is bigger than than n of the destination, a null terminator will not be appended, so after the call to strncat you should add it yourself:

    strncat(dest, "values", sizeof(dest) -1 );
    dest[sizeof(dest) - 1] = '\0';
    

    Last thing, since this is strncat, and it copies to wherever the destination string terminates, the size calculation is slightly more complex and is actually:

    strncat(dest, "values", total_size_of_dest_buffer - strlen(dest) - 1 );