Confusion about character pointers in C

Character pointers in C confuse me.

Suppose we have a char pointer that points to the first character of a string constant .

char *a="ABCD"; 

Then we cannot change the value of this symbol using the a pointer, since the following statement leads to a segmentation error.

 *a='X'; 

Now suppose we have a char pointer that points to a constant character.

 const char B='X'; char *ptr=&B; 

Then we are allowed to change the value of this symbol using the operator

 *ptr='Z'; 

My question is, is this a case of undefined behavior proving that C is not reliable? Or is there some deeper logic?

+5
source share
3 answers

The reason the pointer behaves differently is because C has several memory segments, some of which are protected.

Then we cannot change the value of this symbol using the a pointer, since the following statement leads to a segmentation error.

Unlike other constants, string constants are placed in a protected segment. Any attempt to change this segment results in undefined behavior (i.e. your program may segfault).

Because your pointer points to a string constant, the value it points to cannot be changed. If you force a constant to be copied to the modified memory using an array, the same modification will be allowed:

 char a[]="ABCD"; *a='X'; 

Then we are allowed to change the value of this [single] character using the operator

This is because the character constant is always copied to mutable memory.

+5
source

Say that C allows you to easily shoot in the foot. Modification of B still remains undefined behavior, just as changing *a was because B was declared const .

To help with this, the inclusion of warnings (which you should always do, unless under special circumstances) triggers the following in GCC:

 warning: initialization discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers] 
+7
source

In C, string literal modifications are not allowed.

 char *a="ABCD"; 

equivalently

 char const *a="ABCD"; 

*a='X'; modifies the string literal ABCD . In the second case, ptr points to a character that should not be changed, and *ptr='Z'; will modify the contents of the location containing X , which is also invalid.

Note that modifying the <qualified const object is a violation of the constraint.

+5
source

All Articles