I'm studying pointers on my own and have a doubt about lifetime. Look at this example:
int* fun(){
int arr[10];
for(size_t c = 0;c<10;c++){
arr[c] = c + 10;
}
return arr;
}
int main() {
int* p;
p = fun();
printf("%p",p);
}
This example obviously will print a null address, because the array have been freed after function is finished. To fix it I've tried malloc and it have worked.
After my success I've tried another code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int* fun(){
int arr[10];
for(size_t c = 0;c<10;c++){
arr[c] = c + 10;
}
int* arr2 = arr;
return arr2;
}
int main() {
int* p;
p = fun();
printf("%p",p);
}
Based on my studies, this example should print a null address again, but it have worked as well as the malloc solution. I can't understand why this happen. If the int arr[10]
is freed, it's pointers should point to null right?
This example obviously will print a null address
No. The address returned from the function will be indeterminate, meaning it has no deterministic value. Likely it is the same address as where arr
used to be, but the compiler is free to print anything it pleases, or treat the whole thing as a "trap representation" meaning it may toss an exception/signal etc when this happens.
When I run your code in gcc it decided to print "(nil)" output. While clang felt that the "obvious" result should be 0x7ffef0b3c870
. The program might as well print 0xDEADBEEF
and that would be conforming as well.
Based on my studies, this example should print a null address again
Your studies are based on wrong conclusions. You watched a car crash and it landed upside-down, then made the conclusion that when cars crash they always land upside-down.
In either of your examples, the value of the returned pointer is indeterminate.
Sources
C17 6.2.4/2:
If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
C17 3.19.2:
indeterminate value
either an unspecified value or a trap representation