CodeQL documentation

Returning stack-allocated memory

ID: cpp/return-stack-allocated-memory
Kind: path-problem
Security severity: 9.3
Severity: warning
Precision: high
Tags:
   - reliability
   - security
   - external/cwe/cwe-825
Query suites:
   - cpp-code-scanning.qls
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

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.

Recommendation

Use the functions of the malloc family, or new, to dynamically allocate memory on the heap for data that is used across function calls.

Example

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.

Record *mkRecord(int value) {
	Record myRecord(value);

	return &myRecord; // BAD: returns a pointer to `myRecord`, which is a stack-allocated object.
}

To fix this, allocate the object on the heap using new and return a pointer to the heap-allocated object.

Record *mkRecord(int value) {
	Record *myRecord = new Record(value);

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

References

  • Common Weakness Enumeration: CWE-825.

  • © GitHub, Inc.
  • Terms
  • Privacy