bornfree
bornfree

Reputation: 2528

Garbage values in pointer array

#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?

Upvotes: 2

Views: 1196

Answers (2)

phoeagon
phoeagon

Reputation: 2090

int j=10;

is a local variable allocated on stack. Dereferencing it outside the function is undefined behaviour. WARNING: Never ever return a pointer to any local variable unless you are pretty sure what you are doing. If you are sure, think about it again.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206498

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.

Upvotes: 9

Related Questions