C : Random memory location for variable but constant location for string

While I am doing the Week 4 (Memory) source code exercise, I notice:

– Variable address is always changing

– String address is always the same.


Address5.c – variable address always different
Direct example of random variable address
Address6.c – string (1st char) pointer address always same
Direct example of string liberal address

RAM always assign random location to the variable as explain in CS50 lecturer, but I am not sure why string address is always the same. After asking in CS50 Discord, @Blauelf answered as below.

“The global constants are always in the same location (within the virtual address space). Because string literals are stored there, the compiler can write a constant value for initialising s. The rest… I guess that’s the result of Address Space Layout Randomisation ASLR https://en.wikipedia.org/wiki/Address_space_layout_randomization

I found something at the stakeoverflow:

The standard: ISO/IEC 14882:2003 says:

2.13. String literals

  1. […]An ordinary string literal has type “array of n const char” and static storage duration (3.7)
  2. Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation- defined. The effect of attempting to modify a string literal is undefined.
"It simply means that due to string liberals memory location is constant, therefore the string location is constant. However, the variable location is randomize."