3 ms·
what's inefficient about it?
by halayli 11y ago
what's inefficient about it?
- sepeth 11y agoIt puts zeros to unused bytes in the destination. Here's a note from its man page: Some programmers consider strncpy() to be inefficient and error prone. If the programmer knows (i.e., includes code to test!) that the size of dest is greater than the length of src, then strcpy() can be used. One valid (and intended) use of strncpy() is to copy a C string to a fixed-length buffer while ensuring both that the buffer is not overflowed and that unused bytes in the target buffer are zeroed out.
- ambrop7 11y agoThe typical strcat code you see in the wild: char buf[100]; buf[0] = '\0'; strcat(buf, "Hello"); strcat(buf, " "); strcat(buf, "World"); strcat(buf, "!\n"); The inefficiency is that each time you do strcat, the existing characters of the string are iterated. So something like a common sequence of building a string by appending little pieces has quadratic inefficiency.
- halayli 11y agoThis is a C problem in general. You can create your own data structures and use str.buf + str.len.
- bmm6o 11y agoIt's unfortunate that strcat & friends don't return a pointer to the new end of the string, or a count of the characters copied. You could use those to make subsequent cats more efficient.