Showing posts with label strncpy. Show all posts
Showing posts with label strncpy. Show all posts

Common mistakes when using buffer sizing functions such as strncpy, snprintf, and strncmp

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

Using strcpy, strncpy, sprintf, and snprintf safely

strcpy: The length of src must be less than the length of dst.


char *src = "AAA";
char dst[10] = { 0, };
if (strlen(src) < sizeof(dst) {
	strcpy(dst, src);
}

strncpy: If the length of src is greater than or equal to dst, the '\0' at the end of dst disappears, so dst length - 1 should be set as n.


char *src = "AAA";
char dst[10] = { 0, };
strncpy(dst, src, sizeof(dst) - 1);

sprintf : The format string must not exceed dst.

snprintf : Set the length value keeping in mind that '\0' is entered at the end of the length n.


char *src = "aaaaa"
int src2 = 10000

char dst[10] = { 0, };

snprintf(dst, sizeof(dst), "%s%d", src, src2); // "aaaaa1000" The last character is truncated.

Lognote - Log viewer, Android logcat viewer for Windows, Linux, Mac

android logcat viewer for Windows, Linux, Mac   https://github.com/cdcsgit/lognote Filtered log viewer Android logcat viewer, kotlin ...