Jump to content
  • Advertisement
Sign in to follow this  
IFooBar

safe to assume multiple instances of same stirng have same address?

This topic is 5109 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Would it be safe to assume that multiple instances of constant strings will always always have the same address in memory? Like take this for example:
void f()
{
    std::cout<< (int)"hap656456546py"<< std::endl;
    std::cout<< (int)"gipp"<< std::endl;
    std::cout<< (int)"happy"<< std::endl;
    std::cout<< (int)"gipp"<< std::endl;
    std::cout<< (int)"happy"<< std::endl;
    std::cout<< (int)"hap656456546py"<< std::endl;
}

int main()
{
    f();
    std::cout<< std::endl;
    std::cout<< (int)"hap656456546py"<< std::endl;
    std::cout<< (int)"gipp"<< std::endl;
    std::cout<< (int)"happy"<< std::endl;
    std::cout<< (int)"gipp"<< std::endl;
    std::cout<< (int)"happy"<< std::endl;
    std::cout<< (int)"hap656456546py"<< std::endl;
    std::cout<< std::endl;
    f();
}

This confirms my assumption a bit, but I need to know if this is the "standard" beahvior and it will always work. Thanks.

Share this post


Link to post
Share on other sites
Advertisement
No, this is purely a compiler optimization. I would assume at least a few compilers wouldn't do it if the optimizations were turned off.

Share this post


Link to post
Share on other sites
Quote:
Original post by IFooBar
Would it be safe to assume...


As hh10k said, this is a compiler optimization. Some compilers may have flags to support this, which should allow safe assumption of this WITHIN THE SAME TRANSLATION UNIT (read: object file). But as a "general" rule it is not a safe assumption.

Share this post


Link to post
Share on other sites
You can make that more likely in MSVC.NET by changing the following option:

Project properties ->
Configuration Properties ->
C/C++ ->
Code Generation ->
Enable String Pooling = Yes


However, as mentioned above, relying on specific compiler behaviour for things like this should be considered extremely bad (and dangerous) practice.

If you need shared strings at a specific address, then do it explicitly.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!