CodeQL documentation

Returning stack-allocated memory

ID: cpp/return-stack-allocated-memory
Kind: path-problem
Security severity: 9.3
Severity: warning
Precision: high
   - 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.


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


Record* fixRecord(Record* r) {
	Record myRecord = *r;
	delete r;

	return &myRecord; //returns reference to myRecord, which is a stack-allocated object


  • Common Weakness Enumeration: CWE-825.

  • © GitHub, Inc.
  • Terms
  • Privacy