Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are string references duplicated? [duplicate]

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?

like image 382
Fabricio Avatar asked Feb 08 '12 21:02

Fabricio


People also ask

Can strings have duplicates?

To find the duplicate character from the string, we count the occurrence of each character in the string. If count is greater than 1, it implies that a character has a duplicate entry in the string. In above example, the characters highlighted in green are duplicate characters.

Why string literals should not be duplicated?

Background Information: String literals should not be duplicated Duplicated string literals makes the process of refactoring error-prone, since you must be sure to update all occurrences. On the other hand, constants can be referenced from many places, but only need to be updated in a single place.

Which string function duplicates a string?

The C library function to copy a string is strcpy(), which (I'm guessing) stands for string copy. Here's the format: char * strcpy(char * dst, const char * src);

What is string deduplication?

String Deduplication is a Java feature that helps you to save memory occupied by duplicate String objects in Java applications. It reduces the memory footprint of String objects in Java heap memory by making the duplicate or identical String values share the same character array.


2 Answers

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"

like image 127
ouah Avatar answered Oct 01 '22 16:10

ouah


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...

like image 29
rodrigo Avatar answered Oct 01 '22 14:10

rodrigo