0

Suppose I have this block of code:

#include <stdio.h>
#include <unistd.h>

int *local_pointer(void)
{
    int x = 6;
    return &x;
}

void add(void)
{
    int a;
    a = 4;
    a = a + 1;
}

int main()
{
    int *result;
    result = local_pointer();
    printf("int is %d\n", *result);
    add();
    printf("int is %d\n", *result);
    return 0;
}

The output of this code is

int is 6
int is 5

I am confused as to why this is?

If we go through main, the result variable is returned a pointer to x and then when it the pointer is dereferenced the its value is 6 however why does calling the add function make the next printf statement print 5?

bigfocalchord
  • 553
  • 1
  • 7
  • 14

2 Answers2

3

Your code has a bug. Your local_pointer function returns a pointer to its x variable. But as soon as that function returns, x no longer exists since it was local. So when you dereference the returned pointer, the results are undefined.

If I had to guess, I'd say that a happens to occupy the memory that x used to occupy. But that's just a guess. The behavior might be due to something else. It might change with compiler options. It might change with a different compiler. Who knows? Fix the bug and the mystery will go away.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • 1
    With optimization, the `add()` function and the call to it might be optimized away since they have no visible effect on the computation. Then you might get 6 twice, or might get yet another result. – Jonathan Leffler Aug 27 '19 at 06:53
0

The function local_pointer probably (cf. other comments on undefined behaviour) returns a pointer to the stack. So I think you are basically printing the content of the stack. The call to add writes the value 5 to the stack, that's what your second printf is outputing 5.

Guillaume Petitjean
  • 2,408
  • 1
  • 21
  • 47