Here
int *foo(int x) {
x- local non-static variable. Performing
return &x;
you are returning the address of a local variable x. It exists as long as the function executes, and when the function completes, this address will be invalid for you. Using
*pt = 17;
You are looking for this address and writing 17to this invalid memory location. This causes Undefined Behavior . This is why this code is bad.
source
share