0
main()
{
  char *c="abhishek";
  int i;
  c[2]=90;
  for(i=0;i<12;i++)
  {
    printf("%c",c[0])
  }
}

Here the output is abZishek. But this should result in a bus error because this is a string literal and we can not change its value. Why does the value of c change?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
user3335653
  • 133
  • 1
  • 8

2 Answers2

7

According to section 2.14.5 paragraph § 11 of the C++ standard, it invokes undefined behavior:

The effect of attempting to modify a string literal is undefined.

This means anything can happen and indeed something has happened. You must not make any assumptions about what may happen when you invoke undefined behavior.

Community
  • 1
  • 1
4pie0
  • 29,204
  • 9
  • 82
  • 118
3

"Undefined behaviour" does not guarantee a "bus error" or any other sort of error. In general it cannot be easily detected so your compiler is not required to bother. Here, it does not bother. However, in doing this you may cause unpredictable or strange things to happen.

You're also missing library includes and a return type for main; which C++ book are you using?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • i did not not include libraries because it is obvious.what is the need to include.I am a final year student in Btech and a want to be a java programmer>and i am certified in java .i want to read c and c++ only up to level that i can pass the written test of compnies.i am using test your c skills in c for practice and head first c for theory.What else i should use?? – user3335653 Feb 22 '14 at 05:29
  • @user3335653: It's not "obvious" to use at all that you've been including the correct ones if you don't show them to us. Here is your book recommendation: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Lightness Races in Orbit Feb 22 '14 at 15:42