1

I am refreshing my memory of C, and I wanted to test pointers.

I did this simple program, where I call a function that returns a pointer to the largest integer among it's arguments

int*function_pointer (int a, int b, int c);

int main ()
{
      printf("Testing pointers\n");// line 1

      int*pointer = pointer_function(10,12,36);
      //pointer_function(10,102,36) is assigned to int*pointer

      printf("Okay, what now...\n");//line 3


      return 0;
}

the pointer function

int*function_pointer (int a, int b, int c)
{
     int x;
     int*ptr = &x;
     //initially ptr points to the address of x

     if(a > b)
     {
          if(a > c)
          {
               printf("a is the greatest\n);
               ptr = &a;
          }
     }

     if(b > a)
     {
          if(b > c)
          {
              printf("b is the greatest\n");
              ptr = &b;
              //b is 102, so in this scope ptr points to the address of b
          }
     }

     if(c > a)
     {
          if(c > b)
          {
              printf("c is the greatest\n");
              ptr = &c;
          }
      }

      return ptr;
      //function returns the value of ptr which is the address of b
}
  • at main function function_pointer(10,102,36) is called
  • inside function_pointer(...), int a, b, c are created for that scope
  • initially ptr = &x
  • since b = 102, ptr = &b
  • the functions returns the value of ptr
  • at main pointer = ptr, hence pointer = &b
  • but b is out of scope, and doesn't have any content
  • so how come *pointer = 102, shouldn't it return a garbage value since b is not withing the scope of the main function
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Embedded_Dude
  • 227
  • 3
  • 9
  • Possible duplicate of [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – msw Mar 11 '18 at 11:59

1 Answers1

1

but b is out of scope, and doesn't have any content

Your pointer is technically still valid and it just points to memory area. It your case it, when function_pointer() returns the b still points to memory it was using for local variable (so, in this case on your stack). You should not use the memory any longer, but as memory content your pointer points to is by default not zeroed when no longer used, then you are simply lucky to still have previous value 102 still there, because as your stack did not expand more than since function_pointer() returned as no other code needed to do that.

If you want do to do some tests, you may want to create another function that you call after function_pointer(). If that new function you need to local variables (i. e. array of 150 ints). to make your code to use more stack and overwrite leftovers. Then you will no longer see 102.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141