5

Possible Duplicate:
C/C++: Optimization of pointers to string constants

Suppose you have a string "example" defined in a lot of places

// module1.h
char *x = "example";
// module2.h
char *a[] = { "text", "example" };
// module3.c
printf("example");
//etc.

Will this data will be duplicated or will the compiler makes only one reference to it?

Community
  • 1
  • 1
Fabricio
  • 7,705
  • 9
  • 52
  • 87
  • Depends on the compiler/linker and the options. I believe whole program optimization and a smart linker will combine duplicates but don't remember the reference materials. – JimR Feb 08 '12 at 21:42

3 Answers3

8

It is implementation dependent. But that was the spirit of the immutable property of string literals.

Quoting from the C99 Rationale on string literals:

"String literals are not required to be modifiable. 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"

ouah
  • 142,963
  • 15
  • 272
  • 331
2

That is an "implementation detail". This means that some smart compilers will unify the strings in memory while others will make separated copies.

And lastly, some compilers will do one thing with certain compiler options and other things with other options...

rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • This is not *implementation defined* in the sense that the implementation does not have to document this implementation detail (as required with implementation defined behaviors) but of course this is implementation dependent. – ouah Feb 08 '12 at 21:49
  • @ouah In other words, it's documented as being undocumented ;-) – Neil Feb 08 '12 at 21:54
  • @ouah - Subtle detail, and good clarification. Edited the answer to avoid confusion. – rodrigo Feb 08 '12 at 22:12
0

That is an implementation detail and compiler writers are free to do it any way they want. Many compilers do have a switch to control whether or not duplicate string constants refer to the same address.

Ferruccio
  • 98,941
  • 38
  • 226
  • 299