C++: Add a second example.

This commit is contained in:
Geoffrey White
2024-05-08 11:25:42 +01:00
parent 575b66a054
commit 486226814a
3 changed files with 42 additions and 0 deletions

View File

@@ -31,6 +31,15 @@ Reviewing the code above, the issue can be fixed by simply deleting the additona
not to free <code>new_buffer</code> as this pointer is returned by the function.
</p>
<sample src="DoubleFreeGood.cpp" />
In the next example, <code>task</code> may be deleted twice, if an exception occurs inside the <code>try</code>
block after the first <code>delete</code>:
</p>
<sample src="DoubleFreeBad2.cpp" />
<p>
The problem can be solved by assigning a null value to the pointer after the first <code>delete</code>, as
calling <code>delete</code> a second time on the null pointer is harmless.
</p>
<sample src="DoubleFreeGood2.cpp" />
</example>
<references>

View File

@@ -0,0 +1,16 @@
void g() {
MyTask *task = NULL;
try
{
task = new MyTask;
...
delete task;
...
} catch (...) {
delete task; // BAD: potential double-free
}
}

View File

@@ -0,0 +1,17 @@
void g() {
MyTask *task = NULL;
try
{
task = new MyTask;
...
delete task;
task = NULL;
...
} catch (...) {
delete task; // GOOD: harmless if task is NULL
}
}