1

I have 2 questions regarding that code:

char* word="Hello World";
word[0]='a';
printf("%s",word);

I know that when you creat a string like this, you can't change the string because it is a constant string, so I don't understand why I can run this code and not have any error(I Use Code Blocks C99)? and another weird thing is that the word isn't really changing, the printf still prints:"Hello World".

Michael
  • 427
  • 1
  • 3
  • 13
  • Detecting undefined behavior is undecidable in general (and the C standard does not require compilers to warn or produce errors when it appears). Still, you're right that it'd be possible for the compiler to detect this case. – Paul Hankin Feb 16 '14 at 09:27

2 Answers2

5

When you try to modify string literal then it invokes undefined behavior. The result may be expected or unexpected. Either it will print Hello World or aello World or it can also print nothing. You may get segmentation fault or any unexpected behavior.

haccks
  • 104,019
  • 25
  • 176
  • 264
0

To get the error declare as

const char * word="hello world";

In your case, it may crash at run time as hello world is stored at read-only memory.

Generally

const char * and char * are practically same, but the difference is that if you try to edit the string then const char * shows error at compile-time whereas char * shows error at run-time.

zee
  • 188
  • 2
  • 2
  • 9