6

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?

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

11 Comments

Actually it isn't undefined. Dereferencing it is undefined. Since it always has a valid address when dereferenced, it's a valid program.
@StoryTeller, cout << c << endl; does dereference the pointer.
@StoryTeller The output operator uses dereferencing.
@StoryTeller: Reading the content pointed to by c is actually dereferencing. dereferencing doesn't necessary mean the usage of * as you might probably think.
@StoryTeller, it does not get updated with the new address. c is a static variable and is initialized only in the first call to the function.
|
1

You have Undefined Behaviour in your code so those results may vary. The UB is because call test("Hello"); creates a temporary which then you assign to static local variable. This temporary is destoryed after a call ends, so the pointer in test function is dangling. If you use it then you have undefined behaviour.

It is possible that memory manager reuses the same memory region, so that you see Hello and Nooo in your results.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.