c++ - const char * value lifetime -


this question has answer here:

edit: question why code in question works has been answered linked question in duplicate marking. question string literal lifetime answered in answer question.

i trying understand how , when string pointed const char * gets deallocated.

consider:

const char **p = nullptr;  {     const char *t = "test";     p = &t; }  cout << *p; 

after leaving inner scope expect p dangling pointer const char *. in tests not. imply value of t continues valid , accessible after t gets out of scope.

it due prolonging lifetime of temporary binding const reference. no such thing , saving reference t in member variable , printing value different function later still gives me correct value.

class cstringtest { public:     void test1()     {          const char *t = "test";         m_p = &t;         test2();     }      void test2()      {          cout << *m_p;     }  private:     const char **m_p = nullptr; }; 

so lifetime of t's value here? invoking undefined behaviour dereferencing pointer value of variable went out of scope. works every time think not case.

when trying other type qstring:

qstring *p = nullptr;  {     qstring str = "test";     p = &str; }  cout << *p; 

the code prints value correctly though should not. str went out of scope value , have not prolonged lifetime binding const reference either.

interestingly class example qstring behaves expect , test2() prints gibberish because value indeed went out of scope , m_p became dangling pointer.

so actual lifetime of const char *'s value?

the variables p , t stack variables declared, have lifetime ends @ end of enclosing block.

but value of t address of string literal "test", , not variable declared, it's not on stack. it's string literal, constant defined in program (similar integer literal 99 or floating point literal 0.99). literals don't go out of scope expect, because not created or destroyed, are.

the standard says:

evaluating string-literal results in string literal object static storage duration, initialized given characters specified above.

so object compiler creates represent literal "test" has static storage duration, same duration globals , static variables, meaning doesn't go out of scope stack variable.

the value of p address of t, does become invalid pointer when t goes out of scope, doesn't mean value stored @ address becomes inaccessible or gets wiped. expression *p undefined behaviour, appears work because nothing has reused memory location yet *p still contains address of string literal. more details on see top answer can local variable's memory accessed outside scope?


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -