Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value pointed to by a pointer changes after first dereference

Tags:

c

pointers

I am trying to initialize the integer pointer "p" inside the "init_pointer" function. After the function returns I am printing the pointer and the dereferenced value twice. The first dereference prints the expected value 100, but the second dereference prints random values.

#include<stdio.h>

    void init_pointer(int d, int **c){
            (*c) = &d;
    }

    int main(){
            int x = 100;
            int *p;

            init_pointer(x,&p);

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

            return 0;
    }

Output:

pointer = 0x7fffb4d4b9ac, value = 100
pointer = 0x7fffb4d4b9ac, value = 32567
like image 848
IAmStarDust Avatar asked Dec 31 '25 21:12

IAmStarDust


2 Answers

The function has copied the value to a new local variable in init_pointer(int d, int **c)

d is local to init_pointer which was passed by main from x. Both x and d are separate variables whose addresses are different. Accessing the address of d outside init_pointer will lead to Undefined Behavior.

It would not make sense to call the function like this but this will work:

void init_pointer(int *d, int **c)
{
        (*c) = d;
}

int main()
{
        int x = 100;
        int *p;

        init_pointer(&x,&p);

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

        return 0;
}

Output:

pointer = 0xbfde132c, value = 100
pointer = 0xbfde132c, value = 100
like image 146
Sadique Avatar answered Jan 03 '26 11:01

Sadique


void init_pointer(int d, int **c){
        (*c) = &d;
}

Here *c points to a local copy inside init_pointer(). Once init_pointer() returns, the address becomes invalid, and p in main() points to a freed address.

like image 29
timrau Avatar answered Jan 03 '26 10:01

timrau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!