Skip to content

Commit 8a261b7

Browse files
committed
C++: Update StrncpyFlippedArgs.qhelp.
1 parent 06d8892 commit 8a261b7

File tree

3 files changed

+26
-4
lines changed

3 files changed

+26
-4
lines changed

cpp/ql/src/Likely Bugs/Memory Management/StrncpyFlippedArgs.qhelp

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"qhelp.dtd">
44
<qhelp>
55
<overview>
6-
<p>The standard library function <code>strncpy</code> copies a source string to a destination buffer. The third argument defines the maximum number of characters to copy and should be less than
6+
<p>The standard library function <code>strncpy</code> copies a source string to a destination buffer. The third argument defines the maximum number of characters to copy and should be less than
77
or equal to the size of the destination buffer. Calls of the form <code>strncpy(dest, src, strlen(src))</code> or <code>strncpy(dest, src, sizeof(src))</code> incorrectly set the third argument to the size of the source buffer. Executing a call of this type may cause a buffer overflow. Buffer overflows can lead to anything from a segmentation fault to a security vulnerability.</p>
88

99
</overview>
@@ -12,9 +12,14 @@ or equal to the size of the destination buffer. Calls of the form <code>strncpy(
1212
not the source buffer.</p>
1313

1414
</recommendation>
15-
<example><sample src="StrncpyFlippedArgs.cpp" />
1615

16+
<p>In the following examples, the size of the source buffer is incorrectly used as a parameter to <code>strncpy</code>:</p>
1717

18+
<example><sample src="StrncpyFlippedArgsBad.cpp" />
19+
20+
<p>The corrected version uses the size of the destination buffer, or a variable containing the size of the destination buffer as the size parameter to <code>strncpy</code>:</p>
21+
22+
<example><sample src="StrncpyFlippedArgsGood.cpp" />
1823

1924
</example>
2025
<references>
Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,9 @@
1-
strncpy(dest, src, sizeof(src)); //wrong: size of dest should be used
2-
strncpy(dest, src, strlen(src)); //wrong: size of dest should be used
1+
char src[256];
2+
char dest1[128];
3+
4+
...
5+
6+
strncpy(dest1, src, sizeof(src)); // wrong: size of dest should be used
7+
8+
char *dest2 = (char *)malloc(sz1 + sz2 + sz3);
9+
strncpy(dest2, src, strlen(src)); // wrong: size of dest should be used
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
char src[256];
2+
char dest1[128];
3+
4+
...
5+
6+
strncpy(dest1, src, sizeof(dest1)); // correct
7+
8+
size_t destSize = sz1 + sz2 + sz3;
9+
char *dest2 = (char *)malloc(destSize);
10+
strncpy(dest2, src, destSize); // correct

0 commit comments

Comments
 (0)