0
char* p ="good"; 
p[2] = 'a';

What I understand that good is stored in read only memory. So It can not be modified. But in Visual studio 8, it is not giving any error. Can anybody explain what is happening here.

user966379
  • 2,823
  • 3
  • 24
  • 30

3 Answers3

3

What you are doing is undefined behavior. This means that you cannot guess what is going to happen because it's going to depend on the compiler, OS, weekday and phase of the moon.

In some cases you will see it "working" as if you were allowed to write, in other cases you may get a crash... in other cases you can have that change to mutate both that string and other strings (e.g. a string literal containing "hmmm... this is good" from another part of the program).

In C and in C++ you cannot expect the system to help you when you make a mistake... the assumption is simply that you will not make mistakes. So just don't do that.

There are no runtime error angels to help you in these languages, just undefined behavior daemons waiting to have fun of you by making you cry.

6502
  • 112,025
  • 15
  • 165
  • 265
1

UB is not required to "give an error" in the sense of reporting a problem to the programmer or the user. Merely invoking UB is an error, and you have to be aware of this and not do it.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
0

Since you declared p as char * and not const char *, you are "allowed" to change the content p points to from the compiler's point of view and crash at runtime, but you should get at least a warning for assigning a string constant to char *.

In other words, this is the problem:

char* p ="good"; 

but you will crash here:

p[2] = 'a';
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
MByD
  • 135,866
  • 28
  • 264
  • 277