I am taking a c programming course on Udemy and am quite confused when passing a double pointer into a function. In the example, the instructor passes the address of a pointer as an argument to a function. Then, he de-references that double pointer parameter in the function and sets it equal to the address of a local variable (a).
#include <stdio.h>
#include <malloc.h>
void foo(int **temp_ptr)
{
int a = 5;
*temp_ptr = &a;
}
int main()
{
int *ptr = NULL;
ptr = (int*) malloc(sizeof(int));
*ptr = 10;
foo(&ptr);
printf("%d\n", *ptr);
return 0;
}
So, what we are doing here is changing the value of ptr
to hold the address of a
. Then, when we de-reference ptr
, it should display the value of 5
and not 10
, since we changed the value of ptr
to hold the address of a
.
This is indeed correct: it displays 5 and not 10.
However, what doesn't make sense here is that the variable a
is in the local scope of the foo
function. When we declare a
, the memory allocated is put onto the stack frame; thus, when leaving the local scope of the function that memory is deleted and the frame is popped off of the stack. How can we still access that variable a with the ptr
variable in the main function? Shouldn't that memory be completely wiped out?
CodePudding user response:
Then, when we de-reference
ptr
, it should display the value of 5
Should is incorrect. printf("%d\n", *ptr);
is undefined behavior (UB) as the address stored in ptr
is invalid with the return of foo(&ptr);
.
Output may print 5, may print 42, may crash. It is UB.
... correct that the memory of the stack should be completely wiped out
No. There is not specified wiping of memory. The result is UB.
But sometimes undefined behavior works?
"undefined behavior" is undefined. Even if it "works" today, it may not "work" tomorrow.
When we declare a, the memory allocated is put onto the stack frame; thus, when leaving the local scope of the function that memory is deleted and the frame is popped off of the stack.
This assumes an underling code model that is not specified by C. Other real possibilities exist.
How can we still access that variable
a
with theptr
variable in the main function?
As is, no defined way. Alternatively keep the address of a
valid by making a
static
.
CodePudding user response:
In Foo
function, we are updating the address of our pointer. int a
declared in foo
function will be stored at some memory location. Now, we are assigning that location to our ptr(which is okay, ptr can point to any memory location of type int
). But the issue is the value at that location is not in our control and this location can be used for any other purpose which may update the value at that location.
It means that our pointer is now pointing to location that may be updated by any other source.