Its been quite a few times that i have seen code using strcpy() to copy data from a source string to destination. For some or the other reason, strncpy() isn't given a fair chance. Few developers don't want the extra effort of maintaining the length of the source string, and the other few trust their source strings and expect it to be null-terminated.
With strcpy() comes risk of stack/heap overflow when the source string isn't null terminated and this was the basis of many buffer overflow attacks. A better approach would be to use strncpy() provide the length of the source string. Yes, one has to calculate the length of the source string, possibly by using strlen().
So wouldn't strlen() too depend on the null character at the end of the source string? Isn't it too vulnerable to a string which isn't null terminated?
Yes it is, but then what is the worst case with strlen()? It is after all going to read chunks of memory and would never modify any of the memory contents unlike strcpy(), which modifies the destination string.
No comments:
Post a Comment