Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of a static const variable

Tags:

c++

static

I am bit confused about the following C++ code:

#include <iostream>

using namespace std;

void test(const string& str)
{
    static const char * const c = str.c_str();
    cout << c << endl;
}

int main(int argc, char* argv[])
{
   test("Hello");
   test("Nooo");
   return 0;
}

Since the variable c is declared as static and const, shouldn't this be initialized only once and keep its initial value until the process is completed? According to this reasoning, I was expecting the following output:

Hello
Hello

But I got:

Hello
Nooo

Can you clarify why the value of the variable c has been modified between two function calls even though it is a const variable?

like image 397
Giuseppe Pes Avatar asked Jul 25 '16 15:07

Giuseppe Pes


1 Answers

Your program has undefined behavior.

When you pass "hello" to test, a temporary std::string object is created, and from that string c is constructed (which is just a pointer to the data of the string object).

When the function call ends, the temporary std::string object is destroyed, and c becomes a dangling pointer. Using it again is undefined behavior.

In your case, the second temporary std::string object's data has the exact same memory address as the first one, so c points to that data. This is not guaranteed whatsoever.

like image 51
Rakete1111 Avatar answered Sep 30 '22 05:09

Rakete1111