Garbage values in pointer array

c, local-variables

Solution

It is Undefined Behavior. You are storing address of a local variable `j` which does not exist beyond the function. `j` is guaranteed to live only within the function scope `{ }`. Referring to `j` through its address once this scope ends results in Undefined behavior.

Undefined behavior means that the compiler is not needed to show any particular observed behavior and hence it can show any output.

Problem

``` #include <stdio.h> void func(int **); int main() { int *arr[2]; func(arr); printf("value [1] = %d \n",*arr[0]); printf("value [2] = %d \n",*arr[1]); return 0; } void func(int **arr) { int j = 10; arr[0] = &j; arr[1] = &j; } ``` The code gets compiled successfully with gcc. However, the output is: ``` value [1] = 10 value [2] = 32725 ``` The second value is a garbage value. Why is it so? How can i use double pointer correctly to access an array?

Original source