1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

int* make_int_on_stack_and_return_address(int initial_value) {  // BAD!!!!
    int n = initial_value;
    int* a_n = &n;   // Reminder:  &n means "address of n"
    return a_n;
}

int main(int argc, char* argv[]) {

    int* a_n = make_int_on_stack_and_return_address(5);
    int* a_n2 = make_int_on_stack_and_return_address(9999);
    int* a_n3 = make_int_on_stack_and_return_address(9999);
    int* a_n4 = make_int_on_stack_and_return_address(9999);
    int* a_n5 = make_int_on_stack_and_return_address(9999);
    int* a_n6 = make_int_on_stack_and_return_address(9999);
    int* a_n7 = make_int_on_stack_and_return_address(9999);

    printf("*a_n == %d\n", *a_n);
    // PROBLEM:  a_n refers to memory from the make_int_on_stack_and_return_address(…)
    //           stack frame, which was invalidated when that function returned.

    // RULE:  Do not attempt to access STACK memory in a stack frame of a function that
    //        has already returned.
    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2022 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.