Search⌘ K
AI Features

Returning Pointers to Strings

Understand the risks involved in returning pointers to local string variables and how constant string literals stored in read-only memory provide a safe alternative. Learn about memory allocation on the stack and why returning pointers to non-static local variables leads to invalid memory access or program crashes.

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 ...