I am trying to find what the rules are for c and c++ compilers putting strings into the data section of executables and don't know where to look. I would like to know if the address of all of the following are guaranteed to be the same in c/c++ by the spec:
char * test1 = "hello";
const char * test2 = "hello";
static char * test3 = "hello";
static const char * test4 = "hello";
extern const char * test5; // Defined in another compilation unit as "hello"
extern const char * test6; // Defined in another shared object as "hello"
Testing on windows, they are all the same. However I do not know if they would be on all operating systems.
I would like to know if the address of all of the following are guaranteed to be the same in c/c++ by the spec
String literals are allowed to be the same object but are not required to.
C++ says:
(C++11, 2.14.5p12) "Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined. The effect of attempting to modify a string literal is undefined."
C says:
(C11, 6.5.2.5p7) "String literals, and compound literals with const-qualified types, need not designate distinct objects.101) This allows implementations to share storage for string literals and constant compound literals with the same or overlapping representations."
And C99 Rationale says:
"This specification allows implementations to share copies of strings with identical text, to place string literals in read-only memory, and to perform certain optimizations"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With