linux-sysprog · beginner · ~15 min

Why not return a stack address?

Avoid returning a pointer to the thread's dead stack.

Challenge

A thread's stack is gone once it exits, so returning the address of a local dangles. Returning a heap pointer or a by-value integer is safe. Classify a return strategy.

Task

Implement int return_method_safe(const char *how) that returns 1 if the strategy returns data that outlives the thread, else 0.

Input

  • how: a return-strategy name string.

Output

1 for "heap-pointer" or "value-via-intptr"; 0 for "address-of-local".

Example

return_method_safe("heap-pointer")       ->   1
return_method_safe("value-via-intptr")   ->   1
return_method_safe("address-of-local")   ->   0

Input format

how: a return-strategy name.

Output format

1 for strategies that outlive the thread, else 0.

Constraints

Safe: heap-pointer, value-via-intptr. Unsafe: address-of-local.

Starter code

#include <string.h>

int return_method_safe(const char *how) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.