UB or not

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • destination
    New Member
    • Dec 2009
    • 34

    #1

    UB or not

    first code
    Code:
    char * f(void){
        char a[]="C is a very good language";
        return a;
    }
    
    int main()
    {
        char* b= f();
        printf("%s",b);
        getchar();
    }
    second code
    Code:
    int f(void){
        int x=9;
        return x;
    }
    
    int main()
    {
        int i=f();
        printf("%d",i);
        getchar();
    }
    I guess the first code invokes UB because a is a local variable which will be destroyed after the function exits and accessing it in main invokes UB.
    want to know if the second one also invokes UB??
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Please put [code].. [/code] tags round your code.

    The difference in the 2 listings is that in the first f retuns a pointer and main trys to access the data pointed at. In the second listing the number is returnsed from f, main just uses that number it does not use it to obtain access to another memory location.

    Accessing the return value is not undefined behaviour it is always valid but in the first case the return value is used to then access another location that no longer exists.

    Comment

    Working...