Return Stack Address High

A function returns the address of a stack variable will cause unintended program behavior, typically in the form of a crash. Since a subsequent function call is likely to re-use this same stack address.

Detector ID
c/return-stack-address@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1#include <stdio.h>
2#include <stdlib.h>
3
4// Noncompliant: Returning a stack address
5int* returnStackAddressNonCompliant() {
6    int localVar = 42;
7    return &localVar;
8}

Compliant example

1#include <stdio.h>
2#include <stdlib.h>
3
4// Compliant: Returning a heap-allocated address
5int* returnStackAddressCompliant() {
6    int* ptr = (int*)malloc(sizeof(int));
7    *ptr = 42;
8    return ptr;
9}