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.
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}
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}