strncpy, snprintf : specify buffer size as source string size => must specify destination buffer size
There are many cases where the size of src and dst in the same function are the same, so there are few cases where the problem occurs
However, a problem occurs when receiving src as a function argument.
char* src = "012345678";
char dst[5] = { 0, };
strncpy(dst, src, strlen(src)); // buffer overflow
snprintf(dst, strlen(src), "%s", src); // buffer overflow
strncmp: String comparison is used for purposes that do not exceed the buffer size, such as the above function, resulting in unintended results.
When specifying the number, it is used only when only the first n characters of the string need to be compared, and strcmp is used to compare the entire string.
char* str1 = "";
char* str2 = "abcd";
strncmp(str1, str2, strlen(str1)); // return 0 : equal, no character comparison as n value is 0
strncmp(str1, str2, strlen(str2)); // return non-zero value: different
char* str3 = "ab";
char* str4 = "abcd";
strncmp(str3, str4, strlen(str3)); // return 0 : equal, compare the first 2 characters
strncmp(str3, str4, strlen(str4)); // return non-zero value: different
No comments:
Post a Comment