user3672212
user3672212

Reputation:

Why not segmentation fault, at accessing blocked/restricted memory location?

Regarding the code below my question is since the "ptr" is in local block. Then How can it accessed outside the function block. It should be restricted No? just like a normal variable. We are trying to access a memory location that is of another function.

int * add(int a, int b){
    // local pointer variable
    int *ptr=NULL,c=0;
    c = a+b;
    ptr = &c;
    return ptr;
}

int main()
{
    // calling add function and accessing
    // the value received using reference(*).
    printf("%d",*add(2,3));
}

Upvotes: 1

Views: 133

Answers (2)

haccks
haccks

Reputation: 106042

Remember a rule: Never return a pointer to local variable.

The variable c doesn't exist once add returns, so the pointer to it will be invalid.

Upvotes: 0

Yirkha
Yirkha

Reputation: 13838

The variable is created on stack. Stack is allocated by the system with granularity of at least a few kilobytes and is not released, so it does not crash -- the memory is still accessible.

So although you are doing a forbidden and unsafe thing there, it might accidentally work and even show the correct value, because there is no function call in between which would overwrite the stack and the value of c in the meantime.

Upvotes: 2

Related Questions