Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the C++ standard guarantee that string literals are stored in the program binary unadulterated?

Tags:

c++

standards

For example, if you have a program

int main()
{
    const char* str = "1111111111111111111111111111111111111111111";
    printf("%s", str);

    return 0;
}

and you compile it, if you search the generated binary for "1111111111111111111111111111111111111111111", (ignoring issues such as encoding), are you guaranteed to find it, or is it allowable for the compiler to generate code that, for example, allocates heap memory, fills it with '1's using a loop, and then fixes up all references to that string literal to point to the heap memory? (and then ensures that it gets deallocated at the right time, blah blah)

I doubt there's any implementation that actually does this... but would it be standards conforming if it did?

like image 584
Bwmat Avatar asked Oct 10 '13 18:10

Bwmat


2 Answers

C++ doesn't have any concept of a "program binary", so the question doesn't really make sense.

The guarantee is that you get all the characters in the string by incrementing and dereferencing the pointer str, i.e. your string is stored contiguously in memory when the program is running.

like image 90
Kerrek SB Avatar answered Sep 22 '22 17:09

Kerrek SB


Binary storage is not impacted by the C++ standard

like image 45
Tom Swifty Avatar answered Sep 22 '22 17:09

Tom Swifty