"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does Returning a C String Literal from a std::string Function Seem to Work Sometimes, But is Still Undefined Behavior?

Why Does Returning a C String Literal from a std::string Function Seem to Work Sometimes, But is Still Undefined Behavior?

Published on 2024-11-18
Browse:183

Why Does Returning a C String Literal from a std::string Function Seem to Work Sometimes, But is Still Undefined Behavior?

Returning C String Literal from std::string Function and Calling c_str()

In C , returning a C string literal from a std::string function is an ill-advised practice that can lead to undefined behavior. However, a common misconception is that this code should fail, while it appears to work in some cases.

When "it's me!!" is passed to myFunction(), the C string literal is implicitly converted to a std::string object. The returned std::string object points to its internal character buffer, which contains a copy of the string literal. Calling c_str() on the std::string returns a pointer to this buffer.

The potential problem arises because the internal character buffer of the std::string object is not stored in static memory. Once the myFunction() function returns, the std::string object and its internal buffer are destroyed. This means the pointer obtained from c_str() becomes a dangling pointer pointing to deallocated memory.

However, in certain implementations and certain circumstances, the operating system may not immediately reclaim the memory used by the deallocated std::string. This is known as memory persistence. As a result, the operating system mistakenly allows the code to continue accessing the deallocated memory, giving the illusion that the code works correctly.

It's important to emphasize that this behavior is undefined in C . The language standard does not define what happens in this situation, and different implementations may behave differently. Relying on memory persistence is dangerous and can lead to unexpected errors in different contexts or on different operating systems.

Therefore, while the example code may appear to work in some cases, it is still considered undefined behavior and should be avoided. To prevent such issues, it's recommended to return a copy of the string literal from the std::string function rather than a direct pointer to its internal buffer.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3