Search code examples
c++stringbufferstring-literals

Error returning char* in c++ function


I have this function:

char* return_string(){
    char buffer[] = "Hi world!";
    return buffer;
}

bool test08()
{
    char compare[] = "Hi world!";
    int result = strcmp(compare,return_string());
if (result == 0) return true;
return false;
}
int main()
{
if(test08) printf("\nTRUE");
else printf("\nFALSE");
}

Why this code run in c++ Shell and it doesn't in codeblocks v. 13.12 (Segmentation fault); it'll work if i change my char buffer[]= declaration to char *buffer=; i'm a beginner at C++ (easy to know) so please be clear...


Solution

  • Just change the function return_string the following way

    const char* return_string(){
        const char *buffer = "Hi world!";
        return buffer;
    }
    

    The problem with the original function implementation is that the array buffer is a local array of the function with the automatic storage duration that will not be alive after exiting the function.

    In the modified function there is used a string literal that has static storage duration. So you may return a pointer to the first character of the string literal.

    The function test08 can be written simpler

    bool test08()
    {
        char compare[] = "Hi world!";
        return strcmp( compare, return_string() ) == 0;
    }