Skip to content

Commit 4f0d725

Browse files
committed
C++: Add a 'good' example as well.
1 parent d52210d commit 4f0d725

File tree

4 files changed

+20
-14
lines changed

4 files changed

+20
-14
lines changed

cpp/ql/src/Likely Bugs/Memory Management/ReturnStackAllocatedMemory.cpp

Lines changed: 0 additions & 5 deletions
This file was deleted.

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

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,23 @@
55

66

77
<overview>
8-
<p>This rule finds return statements that return pointers to an object allocated on the stack.
9-
The lifetime of a stack allocated memory location only lasts until the function returns, and
10-
the contents of that memory become undefined after that. Clearly, using a pointer to stack
8+
<p>This rule finds return statements that return pointers to an object allocated on the stack.
9+
The lifetime of a stack allocated memory location only lasts until the function returns, and
10+
the contents of that memory become undefined after that. Clearly, using a pointer to stack
1111
memory after the function has already returned will have undefined results. </p>
1212

1313
</overview>
1414
<recommendation>
15-
<p>Use the functions of the <tt>malloc</tt> family to dynamically allocate memory on the heap for data that is used across function calls.</p>
15+
<p>Use the functions of the <tt>malloc</tt> family, or <tt>new</tt>, to dynamically allocate memory on the heap for data that is used across function calls.</p>
1616

1717
</recommendation>
18-
<example><sample src="ReturnStackAllocatedMemory.cpp" />
19-
20-
21-
22-
18+
<example>
19+
<p>The following example allocates an object on the stack and returns a pointer to it. This is incorrect because the object is deallocated
20+
when the function returns, and the pointer becomes invalid.</p>
21+
<sample src="ReturnStackAllocatedMemoryBad.cpp" />
2322

23+
<p>To fix this, allocate the object on the heap using <tt>new</tt> and return a pointer to the heap-allocated object.</p>
24+
<sample src="ReturnStackAllocatedMemoryGood.cpp" />
2425
</example>
2526

2627
<references>
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Record *mkRecord(int value) {
2+
Record myRecord(value);
3+
4+
return &myRecord; // BAD: returns a pointer to `myRecord`, which is a stack-allocated object.
5+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Record *mkRecord(int value) {
2+
Record *myRecord = new Record(value);
3+
4+
return myRecord; // GOOD: returns a pointer to a `myRecord`, which is a heap-allocated object.
5+
}

0 commit comments

Comments
 (0)