Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't modify char* - Memory access violation

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;
  }
like image 737
VextoR Avatar asked Mar 17 '11 18:03

VextoR


2 Answers

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";
like image 97
Prasoon Saurav Avatar answered Oct 13 '22 11:10

Prasoon Saurav


As Prasoon already said, string literals are not modifiable.

If you need a modifiable array of chars have it like this:

char str[] = "HelloGuys";
like image 39
Maxim Egorushkin Avatar answered Oct 13 '22 12:10

Maxim Egorushkin