I'm studying pointers and I've created this example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int* f(){
int n = 10;
return &n;
}
int main() {
printf("%d",*f());
}
The expectation were it would not work, because the returned pointer is pointing to a automatic variable, which will be destroyed, and so we'll have a undefined behavior. And my expectations were correct, the program have crashed.
After it I created a similar example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int* f(){
int n = 10;
int* ptr = &n;
return ptr;
}
int main() {
printf("%d",*f());
}
The only difference in second example is that the function is returning a variable int* ptr
which is of int pointer type, and the initial value of this variable is the address (pointer) of variable int n
.
Before running it I thought it wouldn't work too (I thought it would crash again), but it works, the program don't crash and prints the value '10' at the terminal. My question is: Why the second example works if in theory it is pointing to a automatic variable that will be destroyed
[EDIT]
I've read the comments and I've understand that the second example actually is a undefined behaviour. But I'm still with a doubt: Is There any way to force a "fatal" error that demonstrates this example has an undefined behavior "behind the scenes"? I've created other examples like the second, and all of them have a behaviour that seams right (I know, its a undefined behaviour but nothing special have happened, like a crash your a message)