Global memory optimizations of const char*
I've stumped into an interesting result while trying to understand C++ memory management.
(just a reminder: MinGW 3.4.5 on Win32)
Code:
const char* str1 = "There will be only one";
const char* str2 = "There will be only one";
int main() {
std::cout << std::hex << (int)str1 << " " << (int)str2;
}
Both str1 and str2 point to the same memory location, which is quiet interesting although not something one expect to take much advantage from. However,...
- I couldn't replicate this with any other built-in type. Particularly const arrays of built-in types didn't reproduce this optimization. Why only c-strings?
- I couldn't reproduce this behavior either on the heap or stack. Just on the global space. What prevents this optimization to take place on these other memory locations?