I am learning c programming. Here is some sample code that I cannot seem to understand:
#include <stdio.h>
int* returnArray(){
int arr[4] = {1, 2, 3, 4};
return arr;
}
int main(){
printf("%x", returnArray());
}
If I run this code I get 0 printed out. If I redeclare my local variable in returnArray function as a static local variable, a memory address is printed out. Why do I need to declare the local variable as static before I can print out a hexadecimal memory address? Why am I getting 0 when I don’t use static and what does getting zero mean in terms of what’s going on under the hood?
Below is the code that prints out the memory address:
#include <stdio.h>
int* returnArray(){
static int arr[4] = {1, 2, 3, 4};
return arr;
}
int main()
{
printf("%x", returnArray());
return 0;
}
Also, if I change the function return type and implement differently as below:
#include <stdio.h>
unsigned int returnArray(){
int arr[4] = {1, 2, 3, 4};
return arr;
}
int main()
{
printf("%x", returnArray());
return 0;
}
an actual memory address is returned. Why is that?
>Solution :
Without using static, you’re returning the address of a local variable from a function. That variable’s lifetime ends after the function returns, making the returned value indeterminate.
Accessing an indeterminate value, such as the address of a variable who’s lifetime has ended, causes undefined behavior in your code, which in this case manifests as a value of 0.
This is spelled out in section 6.2.4p2 of the C standard:
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.
Also, it’s undefined behavior to print a pointer value using the %x format specifier, as that specifier expects an unsigned int. You need to use the %p format specifier to print a pointer value, and you need to cast the pointer to void * (one of the few cases where such a cast is required).