Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a locally created const char*

#include <iostream>


const char* fun()
{
    const char* x = "abc";
    std::cout << "x = " << x << "\n";
    return x;
}


int main(int arc, char** argv)
{
    const char* y = fun();
    std::cout << "y = " << y << "\n";
    return 0;
}

Running this on my machine gives:

x = abc

y = abc

In fun(), x (a local variable) is assigned the address of a string literal created locally, yet when the function returns, the data pointed to by y is the same as that pointed to by x even though x is out of scope.

Can someone explain in detail what is happening here?

like image 372
Mode77 Avatar asked Jun 28 '18 02:06

Mode77


People also ask

What does const char * const mean?

In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer. const char* and char const* says that the pointer can point to a constant char and value of char pointed by this pointer cannot be changed.

What is const char * str?

The const char *Str tells the compiler that the DATA the pointer points too is const . This means, Str can be changed within Func, but *Str cannot. As a copy of the pointer is passed to Func, any changes made to Str are not seen by main....

What is const char in C?

const char* is a mutable pointer to an immutable character/string. You cannot change the contents of the location(s) this pointer points to. Also, compilers are required to give error messages when you try to do so. For the same reason, conversion from const char * to char* is deprecated.


1 Answers

This is well-formed, the returned pointer is valid and not dangled; because the string literal (i.e. "abc") has static storage duration and exists in the whole life of the program.

String literals have static storage duration, and thus exist in memory for the life of the program.

As you said when the function returns the local variable x gets destroyed, but the string literal pointed to by it doesn't.

like image 96
songyuanyao Avatar answered Sep 27 '22 17:09

songyuanyao