0

I am posting two codes down. In the first code an unexpected output is coming "ASH-2". The output which must be coming is "ASH35". In the second code, output comes out to be "ASH35". Now if i remove the ' printf("ASH"); ' line in the first code, value 35 gets printed.

Can anyone help me in this unexpected behaviour, thank you in advance for looking into my matter.

//CODE 1

    int* fun()  
    {  
    int k;  
    k=35;  
    return (&k);  
    }

    int main()  
    {  
    int *j;  
    j=fun();  
    printf("ASH");  
    printf("%d",*j);  
    return 0;  
    }


    //CODE 2

     int fun()  
    {  
    int k;  
    k=35;  
    return (k);  
    }

    int main()  
    {  
    int j;  
    j=fun();  
    printf("ASH");  
    printf("%d",j);  
    return 0;  
    }
  • 2
    http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – Mat Jun 21 '16 at 14:50
  • 1
    Your first function returns the address of a local variable so after the function returns the value at this address is undefined. – s7amuser Jun 21 '16 at 14:50
  • @s7amuser Thank you for looking into my matter. Your answer do cleared the fog a it but the remaining thing is when i remove the printf("ASH") line in the first code, then it is working properly. At this time also, address of local variable is undefined, so unexpected value must be printed. But real output comes out to be 35. Why it is so ? Thank you in advance. – Ashish Agarwal Jun 23 '16 at 13:13

0 Answers0