views:

2733

answers:

4

Hi, I have a simple program and I get access violation at *(str + start). why? i should be able to change it. Right?

void fn()
{
     char *str = "Hello wordl!";
     int end = strlen(str);
     int start = 0;
     end--;
     while(start < end)
     {
         *(str + start) = *(str + end);  <--- Access violation writing location *(str + Start).
         end--; start++;
     }
}
+3  A: 

No, you should not. "Hello world" is a constant string literal, you need to allocate memory using malloc() in C, or new in C++ if you want memory you are free to modify.

MattJ
+1  A: 

It's because you're writing to a string literal's storage, which may be in a protected area of memory.

Daniel Earwicker
+6  A: 

char* "Hello World" is a const string, and cannot be modified. The compiler is free to put it into a non-writable location, resulting in the crash you see.

Replacing the declaration with char str[] = "Hello World" should do what you want, putting the string into a modifiable array on the stack.

Michael
Your suggestion would be identical to the current code.
Daniel Earwicker
char str[] versus char* str results in the string being modifiable.
Michael
Here's a couple references to this:http://www.iso-9899.info/wiki/StringsByExamplehttps://www.securecoding.cert.org/confluence/display/cplusplus/STR30-CPP.+Do+not+attempt+to+modify+string+literals
Michael
D'oh, my mistake.
Daniel Earwicker
+1  A: 

As others have pointed out, literal strings may be stored in a read-only area of memory. Are you compiling with warnings turned on? You should get a warning about discarding the constness of the string literal.

What you can do instead is:

char *str = strdup("Hello, world!");
// Modify the string however you want
free(str);
Dan Ellis