Reputation: 227
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
}
function_pointer(10,102,36)
is calledfunction_pointer(...)
, int a, b, c
are created for that scopeptr = &x
b = 102
, ptr = &b
pointer = ptr
, hence pointer = &b
b
is out of scope, and doesn't have any content*pointer = 102
, shouldn't it return a garbage value since b is not withing the scope of the main functionUpvotes: 1
Views: 73
Reputation: 75629
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 int
s). to make your code to use more stack and overwrite leftovers. Then you will no longer see 102
.
Upvotes: 1