Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++: Assorted minor doc improvements #16939

Merged
merged 14 commits into from
Jul 11, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
C++: Add a 'good' example as well.
  • Loading branch information
geoffw0 committed Jul 8, 2024
commit 4f0d725acd188fff20de5874c7e3e64635619c79

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,23 @@


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

</overview>
<recommendation>
<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>
<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>

</recommendation>
<example><sample src="ReturnStackAllocatedMemory.cpp" />




<example>
<p>The following example allocates an object on the stack and returns a pointer to it. This is incorrect because the object is deallocated
when the function returns, and the pointer becomes invalid.</p>
<sample src="ReturnStackAllocatedMemoryBad.cpp" />

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

<references>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Record *mkRecord(int value) {
Record myRecord(value);

return &myRecord; // BAD: returns a pointer to `myRecord`, which is a stack-allocated object.
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Record *mkRecord(int value) {
Record *myRecord = new Record(value);

return myRecord; // GOOD: returns a pointer to a `myRecord`, which is a heap-allocated object.
}