Write a program local variable return value

Returning address of local variable

Question: Is there any problem with the following code?If yes, then how it can be rectified?

int* inc(int val)
  int a = val;
  return &a;

int main(void)
    int a = 10;

    int *val = inc(a);

    printf("\n Incremented value is equal to [%d] \n", *val);

    return 0;
Answer: Though the above program may run perfectly fine at times but there is a serious loophole in the function ‘inc()’. This function returns the address of a local variable. Since the life time of this local variable is that of the function ‘inc()’ so after inc() is done with its processing, using the address of its local variable can cause undesired results. This can be avoided by passing the address of variable ‘a’ from main() and then inside changes can be made to the value kept at this address.


No comments:

Top Blogs