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

1
  • It is illegal to use local variable from some function (j from func) after this function exit. Commented Feb 19, 2013 at 5:38

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

7 Comments

and what about "auto storage class" (storage duration)?
@osgx: What about it? I am sorry I do not understand.
Alok, there is no words "local variable" in some pdf files... e.g. in this file: open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf. Why you think than taking address of smth what you called "local variable" is undefined behavior?
@osgx: The variables with storage class auto are commonly known as local or automatic variables. Automatic since they do not need any explicit cleaning. Though these are not standerdese terminology these are commonly and widely used.
I mean ISO/IEC 9899 "section 6.2.4 paragraph 2,4,5" which actually defines undefined behavior for this case.
|
0
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.

3 Comments

Is there any case when returning address of local variable is legal?
@phoeagon - I am just curious even in undefined behavior why every time on executing this program,it correctly prints the first value.any idea?
Undefined behaviour means compiler can implement whatever they want, it does not necessarily means the runtime behaviour will be different each time you execute it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.