Search code examples
cpointersscopeundefined-behaviorstorage-duration

Returning Local Char Pointer To Array Not Cause Segmantation Fault


Why doesn't this code cause segmentation fault ? I thought after function returns, the content of local variables will be deleted.

char* test(){
    char buffer[BUFSIZ] = "Hello";
    char* word = buffer;

    return word;
}

int* test2(){
    int x = 10;
    int *ptr = &x;

    return ptr;
}

int main() {
    char* str = test();
    printf("str : %s\n", str);

    int *ptr = test2();
    printf("ptr : %d\n", *ptr);

    return 0;
}

Solution

  • The program has undefined behavior because the variables with automatic storage duration declared in the functions are not alive after exiting the functions.

    The program can output the expected result because the memory occupied by the variables was not yet overwritten.

    If to change your program for example the following way

    #include <stdio.h>
    
    char* test(){
        char buffer[BUFSIZ] = "Hello";
        char* word = buffer;
    
        return word;
    }
    
    char* test1(){
        char buffer[BUFSIZ] = "Bye";
        char* word = buffer;
    
        return word;
    }
    
    
    int main( void ) {
        char* str = test();
        printf("str : %s\n", str);
    
        char* str1 = test1();
        printf("str1 : %s\n", str1);
    
        printf("str : %s\n", str);
    
        return 0;
    }
    

    then its output might look like

    str : Hello
    str1 : Bye
    str : Bye
    

    That is the call of the function test1 results in overwriting of the memory early occupied by the array pointed to by the pointer str.