Search code examples
cpointersstructurelocal-variablesvariable-address

Address of local variable is assigned to member pointer in Structure


struct a {
    int *val;
};

void main(){
    int n;
    struct a *a1;
    a1= malloc(sizeof(a1));

    n=10;

    a1->val = &n;

    func(a1);


    printf("After changing %d\n",a1->val);

}

void func(struct a *a2){
    int a = 5;
    a2->val = &a;
    a2->val = 0 ;
}

Assigned local variable to a member structure pointer. and finally making it null. instead of giving null pointer it is giving 0 when tried to access it.


Solution

  • Since a1->val is pointing at an invalid address (19 is very seldom a valid address), you are invoking undefined behaviour and any result is acceptable (including a core dump or other crash).

    Even if your function did:

    *a2->val = 19;
    

    the pointer would be pointing at an integer that is no longer valid when the function returns. Once the function has terminated, it is no longer safe to dereference the pointer; you could safely assign a new pointer value to it; you could compare the pointer to another pointer or NULL (subject to some constraints); but that's about all.