0

I tried running the following program:

#include <iostream>
using namespace std;

int main(){
    char *x = "Linux";
    *x = 'T';
    cout<<"value: "<<*x<<endl;
}

According to me, it should have stored 'T' in the location pointed to by x. But instead it gave segmentation fault. But when I did:

char *x;
*x = 'T';

The output was as expected. Can somebody explain this behavior?

nishantsingh
  • 4,537
  • 5
  • 25
  • 51

2 Answers2

1

Using a non-const char pointer to a string literal is deprecated and should not be used in new code. Modifying a string literal is undefined behavior. Your second example dereferences an uninitialized pointer which is also undefined behavior. That means it can sometimes appear to work.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
0

String literals are const char*s, not char*s.

Both of your examples are undefined behavior; the second one appearing to work only occurs by accident.

James Picone
  • 1,509
  • 9
  • 18