Why is writing to a string literal in this program C segfault?

#include<stdio.h> void main() { char *p="nyks"; p[2]='n'; printf("%s",p); } 

This is a malfunction during Fault SEGMENTATION . Can someone explain why?

+5
c
source share
6 answers

The standard defines that literal strings are defined by const . You cannot change it.

The compiler places the literal in the readonly memory section. You can output the assembly and watch it. If you use GCC, this is done using the -s flag. It will put the string in the .rodata section.

+7
source share

Undefined behavior tries to rewrite a string literal. C99 Β§6.4.5 / 6:

If a program tries to modify such an array, the behavior is undefined.

This is described in Appendix J.2 (undefined behavior).

If you do the following:

 char p[] = "nyks"; 

you can select and initialize an array of characters (stack). In this case, it is perfectly normal to change the elements.

+15
source share

Other answers speak of a look from the standpoint, but that is why it crashes.

Compilers usually put program literals - especially strings - in read-only memory. Memory is read-only by the operating system, so any attempt to write to it falls into the trap, and on your platform this indicates a segmentation error; attempt to perform operation on some memory that is not allowed. Another type of failure associated with misuse of memory is a bus error, which usually indicates either unacceptable memory access or a write to a page that does not appear at all. For C code, the difference is almost entirely academic (some other language implementations use these errors to help them manage memory).

Please note that capturing read-only records is independent of the official language semantics. Although you can point char* to it, you still cannot write it. Always refer to program literals as if they were pointing to read-only memory, and you won’t be mistaken (that they aren’t the default because of the need to maintain compatibility with older programs).

+3
source share

This means (essentially):

  #include<stdio.h> const char privatestring[5] = {"nyks"}; void main() { char *p = const_cast<char*>(privatestring); p[2]='n'; printf("%s",p); } 

The compiler is allowed to put privatestring somewhere where you only have read access. This is const_cast for backward compatibility with programs written before it was the const keyword.

+1
source share

The value is a string literal that cannot be changed, since literals are stored in read-only memory, try p [] instead. Segmentation errors usually occur due to improper use of pointers.

+1
source share

String literals do not change ... Ability to write char *p="nyks"; actually a system hole in C.

0
source share

All Articles