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

It can’t be relied on, it is an optimization which is not a part of any standard.

I’d changed corresponding lines of your code to:

const char* str0 = "Watchmen";
const char* str1 = "atchmen";
char* str2 = "tchmen";
char* str3 = "chmen";

The output for the -O0 optimization level is:

0x8048830
0x8048839
0x8048841
0x8048848

But for the -O1 it’s:

0x80487c0
0x80487c1
0x80487c2
0x80487c3

As you can see GCC (v4.1.2) reused first string in all subsequent substrings. It’s compiler choice how to arrange string constants in memory.

Leave a Comment