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.

No comments:

Lognote - My toy project

In a project, the code work is limited When I say, "I think it will work if I change it like this," I get, "If it doesn't...