In most compilers, when a string value is directly assigned to a pointer, it’s stored in a read-only block (generally in data segment).
This is shared among functions.
when you say char *str = "Test";
"Test" is stored in a shared read-only location, but the pointer str
is stored in a read-write memory and str
is pointing to that memory location in the read-only location. When you assign the same string to a different pointer,
say char* str2 = "Test";
. The str2
pointer will point to the same address from the read only memory location, which is why the output is same.
The following code will fail; the program will crash, because you are trying to change the read only string:
int main() {
char *str;
str = "Test"; // Stored in read only part of data segment
*(str+1) = 'n'; // Trying to modify read only memory. segfault
getchar();
return 0;
}
Creating a string using a char
array is different from creating a string with a char
pointer; the char
array will be created just like other types of arrays in C.
For example,
If str[]
is an auto variable then string is stored in the stack segment.
If str[]
is a global or static variable then stored in the data segment.
int main() {
char str[] = "Test"; // Stored in stack segment like other auto variables
*(str+1) = 'n'; //This is fine
getchar();
return 0;
}
The following code clarifies things:
#include <stdio.h>
char s1[] = "Test"; //Global in data segment
int main() {
char *s2 = "Test"; //Read only
char *s3 = "Test"; //pointed to a string in a Read only memory
char s4[] = "Test"; //stack segment
char s5[] = "Test"; //another array in stack segment
printf("\n%p",s1);
printf("\n%p",s2);
printf("\n%p",s3);
printf("\n%p",s4);
printf("\n%p",s5);
return 0;
}
this will print something like this.
6294408
4196492
4196492
1092092672
1092092656
So you can see that addresses of s1
, s4
and s5
are different.