...
The strcpy_s()
function only succeeds when the source string can be fully copied to the destination without overflowing the destination buffer. The Specifically, the following conditions are treated as a constraint violationchecks are made:
- The source and destination pointers are checked to see if they are null.
- The maximum length of the destination buffer is checked to see if it is equal to zero, greater than
RSIZE_MAX
, or less than or equal to the length of the source string. - Copying is not allowed between objects that overlap.
When a runtime-constraint violation is detected, the destination string is set to the null string (as long as it is not a null pointer and the maximum length of the destination buffer is greater than zero and not greater than RSIZE_MAX
) and the function returns a nonzero value. In the following example, the strcpy_s()
function is used to copy src1
to dst1
.
Code Block |
---|
char src1[100] = "hello"; char src2[78] = {'g','o','o','d','b','y','e','\0'}; char dst1[6], dst2[5]; int r1, r2; r1 = strcpy_s(dst1, sizeof(dst1), src1); r2 = strcpy_s(dst2, sizeof(dst2), src2); |
Wiki Markup |
---|
However, the call to copy {{src2}} to {{dst2}} fails because there is insufficient space available to copy the entire string, which consists of seveneight characters, to the destination buffer. As a result, {{r2}} is assigned a nonzero value and {{dst2\[0\]}} is set to {{"\0"}}. (The {{src2}} string is also not null-terminated, but this is actually irrelevant, since the length provided to {{strcpy_s}} is computed using {{siceof}}.)the null character. |
Users of the ISO/IEC TR 24731-1 functions are less likely to introduce a security flaw because the size of the destination buffer and the maximum number of characters to append must be specified. ISO/IEC TR 24731 Part II (24731-2, in progress) will offer another approach, supplying functions that allocate enough memory for their results. ISO/IEC TR 24731 functions also ensure null termination of the destination string.
...