Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Why does it say "Memory access violation"?

  char* str = "HelloGuys";
  int len = strlen(str);
  for (int i=0; i<(len/2); ++i){
        char t = str[len-i-1];
        str[len-i-1] = str[i]; //error
        str[i] = t;
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
260 views
Welcome To Ask or Share your Answers For Others

1 Answer

String literals are stored in read only section of memory. Any attempt to modify the contents of a string literal invokes Undefined Behaviour (segmentation fault on most implementations).

Use an array of characters rather

char str[] = "HelloGuys";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...