Same strings in array have same memory address

后端 未结 1 1131
庸人自扰
庸人自扰 2020-12-19 15:00

Why do same strings in a char* array have the same address?

Is this because of compiler optimization?

Example:

#include 
#inc         


        
相关标签:
1条回答
  • 2020-12-19 15:39

    It is called constant merging. It is enabled at higher levels of optimization, typically. The compiler simply takes all of the unique constant values and crunches them down. Good for memory usage and cache efficiency.

    gcc has -fmerge-constants or using -O and company

    Other compilers may or may not do it. It is compiler specific.

    Since it is about the easiest optimization operation to implement I would imagine all C++ compilers do it.

    This is a perfect example of why:

    1. You can't make assumptions about where a constant value will live (undefined behavior)
    2. You shouldn't make changes to constant values (undefined behavior)

    but we see many questions about people (not yourself) observing they got away with modifying a constant string after casting away const.

    0 讨论(0)
提交回复
热议问题