-2

Consider the following definition:

char A[]="xyz";

As we all know that A is allocated 4 bytes memory in the stack section when A is defined as above. At the same time will the address of "xyz" be stored in the code section?

iqstatic
  • 2,322
  • 3
  • 21
  • 39

1 Answers1

1

Normally, string literals are stored in read-only memory when the program is run. This is to prevent you from accidentally changing a string constant. The "read-only memory" I am referring to is the text segment in ASM terms. It's the same place in memory where the instructions are loaded. This is read-only for obvious reasons like security. When you create a char* initialized to a string, the string data is compiled into the text segment and the program initializes the pointer to point into the text segment. So if you try to change it you will get a Segfault. However, when written as an array (as in your example), the compiler places the initialized string data in the data segment instead, which is the same place that your global variables etc live. This memory is mutable, since there are no instructions in the data segment. This time when the compiler initializes the character array (which is still just a char*) it's pointing into the data segment rather than the text segment, which you can safely alter at run-time.

iqstatic
  • 2,322
  • 3
  • 21
  • 39
  • Will the character array be initialized in data segment or stack segment.In the above example A (character array) is automatic storage class variable. – yedukondalu Nov 13 '15 at 08:21