Skip to content

Commit 71ad769

Browse files
committed
C++: Add qhelp.
1 parent 204acba commit 71ad769

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<!DOCTYPE qhelp PUBLIC
2+
"-//Semmle//qhelp//EN"
3+
"qhelp.dtd">
4+
<qhelp>
5+
6+
<overview>
7+
<p>Calling <code>c_str</code> on a <code>std::string</code> object returns a pointer to the underlying character array.
8+
However, if the <code>std::string</code> object is destroyed, then the pointer returned by <code>c_str</code> is no
9+
longer valid. If the pointer is used after the <code>std::string</code> object is destroyed, then the behavior is undefined.
10+
</p>
11+
</overview>
12+
13+
<recommendation>
14+
<p>
15+
Ensure that the pointer returned by <code>c_str</code> does not outlive the underlying <code>std::string</code> object.
16+
</p>
17+
</recommendation>
18+
19+
<example>
20+
<p>
21+
The following example concatenates two <code>std::string</code> objects, and then convert the resulting string to a
22+
C string using <code>c_str</code> so that it can be passed to the <code>work</code> function.
23+
24+
However, the underlying <code>std::string</code> object that represents the concatenated string is destroyed as soon as the call
25+
to <code>c_str</code> returns. This means that <code>work</code> is given a pointer to invalid memory.
26+
</p>
27+
28+
<sample src="UseOfStringAfterLifetimeEndsBad.cpp" />
29+
30+
<p>
31+
The following example fixes the above code by ensuring that the pointer returned by the call to <code>c_str</code> does
32+
not outlive the underlying <code>std::string</code> objects. This ensures that the pointer passed to <code>work</code>
33+
points to valid memory.
34+
</p>
35+
36+
<sample src="UseOfStringAfterLifetimeEndsGood.cpp" />
37+
38+
</example>
39+
<references>
40+
41+
<li><a href="https://wiki.sei.cmu.edu/confluence/display/cplusplus/MEM50-CPP.+Do+not+access+freed+memory">MEM50-CPP. Do not access freed memory</a>.</li>
42+
43+
</references>
44+
</qhelp>
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#include <string>
2+
void work(const char*);
3+
4+
void work_with_combined_string_bad(std::string s1, std::string s2) {
5+
const char* combined_string = (s1 + s2).c_str();
6+
work(combined_string);
7+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#include <string>
2+
void work(const char*);
3+
4+
void work_with_combined_string_good(std::string s1, std::string s2) {
5+
auto combined_string = s1 + s2;
6+
work(combined_string.c_str());
7+
}

0 commit comments

Comments
 (0)