Skip to content

Commit 4862268

Browse files
committed
C++: Add a second example.
1 parent 575b66a commit 4862268

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

cpp/ql/src/Critical/DoubleFree.qhelp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,15 @@ Reviewing the code above, the issue can be fixed by simply deleting the additona
3131
not to free <code>new_buffer</code> as this pointer is returned by the function.
3232
</p>
3333
<sample src="DoubleFreeGood.cpp" />
34+
In the next example, <code>task</code> may be deleted twice, if an exception occurs inside the <code>try</code>
35+
block after the first <code>delete</code>:
36+
</p>
37+
<sample src="DoubleFreeBad2.cpp" />
38+
<p>
39+
The problem can be solved by assigning a null value to the pointer after the first <code>delete</code>, as
40+
calling <code>delete</code> a second time on the null pointer is harmless.
41+
</p>
42+
<sample src="DoubleFreeGood2.cpp" />
3443
</example>
3544
<references>
3645

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
void g() {
2+
MyTask *task = NULL;
3+
4+
try
5+
{
6+
task = new MyTask;
7+
8+
...
9+
10+
delete task;
11+
12+
...
13+
} catch (...) {
14+
delete task; // BAD: potential double-free
15+
}
16+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
void g() {
2+
MyTask *task = NULL;
3+
4+
try
5+
{
6+
task = new MyTask;
7+
8+
...
9+
10+
delete task;
11+
task = NULL;
12+
13+
...
14+
} catch (...) {
15+
delete task; // GOOD: harmless if task is NULL
16+
}
17+
}

0 commit comments

Comments
 (0)