String Literals in Translation Units: Reliability of Identical Memory Addresses
String literals are commonly used in programming languages. But is it reliable to rely on the same string literal having the same memory address in different translation units?
Portability of Memory Address Consistency
According to the C99 and C draft standards, the behavior is unspecified whether string literals with identical values have different memory addresses. This means that different implementations may handle this differently.
While some compilers and platforms may offer options for string literal pooling, such as GCC's -fmerge-constants, it's not a guaranteed feature and can vary across systems.
Reliability within a Translation Unit
Within the same translation unit (i.e., a single source file), string literals are typically merged and stored in a single location to optimize memory usage. However, this behavior is implementation-specific and cannot be relied upon for portability.
Example Code
Consider the example code provided:
// foo.c const char *x = "I'm a literal!"; // bar.c const char *y = "I'm a literal!"; // test.c extern const char *x; extern const char *y; assert(x == y);
In this case, the assertion x == y will fail if the compiler does not perform string literal pooling across translation units or if the specific platform doesn't support it.
Conclusion
Relying on identical string literals having the same memory address across translation units is not portable and can lead to unpredictable behavior. However, within a single translation unit, string literals are typically merged for optimization purposes. It's important to consult compiler documentation to understand the specific behavior in each case and use appropriate measures if necessary.
The above is the detailed content of Do Identical String Literals Have the Same Memory Address Across Translation Units?. For more information, please follow other related articles on the PHP Chinese website!