-3

I run the following code

int *pointer;

void fun1() {
    int i;
    pointer = &i;
    *pointer = 11;
}

void fun2() {
    printf("\nFun 2: Hello World\n");
}

int main() {
    pointer = (int*) malloc(sizeof(int));
    *pointer = 0;
    fun1();
    printf("%d\n",*pointer);
    fun2();
    printf("%d\n",*pointer);
    return 0;
}

And the output is

11

Fun 2: Hello World
20

I would expect it to be 11 instead of 20. What am I missing?

Thanks.

kopsti
  • 93
  • 1
  • 9
  • 4
    You are taking a pointer to a local variable. `i` get's invalid/random after your function returns. Possible duplicate to [Why does gcc throw a warning when returning a pointer to a local variable and not when returning a local variable?](http://stackoverflow.com/questions/8184315/why-does-gcc-throw-a-warning-when-returning-a-pointer-to-a-local-variable-and-no) and [returning a local variable from function in C](http://stackoverflow.com/questions/4824342/returning-a-local-variable-from-function-in-c) – Florian Jun 23 '15 at 17:56

3 Answers3

1

This an example of undefined behavior. When fun1 is called, pointer is pointing to an automatic local variable in fun1. Once fun1 completed its execution that variable no longer exist. Now the statement

printf("%d\n",*pointer);  

invoke undefined behavior.
There is also memory leak in your program.

haccks
  • 104,019
  • 25
  • 176
  • 264
0

You set the pointer to local variable i's address in fun1 and it stays that way after fun1 returns. That address is on the stack and later is overwritten with a new value during your call to fun2 and its printf call.

Wormbo
  • 4,978
  • 2
  • 21
  • 41
0

Here in fun1()

pointer = &i;

you assign the global pointer to point to a temporary variable that no longer exists when fun1() exits. Therefore when you call printf with *pointer you are accessing invalid memory.

This is undefined behaviour and trying to understand the content of the invalid memory region afterwards is not worthwile.

mathematician1975
  • 21,161
  • 6
  • 59
  • 101