Returning Pointers to Strings

Learn about the dangers of returning pointers to strings.

Returning pointers to strings

Let’s declare two strings in a function:

char* func()
{
    char str1[]   = "Hello";
    char str2[16] = "World";

    return str1; //return str2;
}

Both str1 and str2 are local variables of func. They get allocated when the function starts executing. Their stack frame is invalidated when the function finishes. Therefore, their memory gets marked as free, and the compiler can reuse it for other functions or variables. Returning a pointer to such a variable is unsafe, as there is no guarantee that the memory will still be valid or contain the data from these two strings.

Consider the following code:

Get hands-on with 1200+ tech skills courses.