How to solve access violation writing location error?
Asked Answered
S

5

13

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++;
     }
}
Selfservice answered 16/3, 2009 at 21:7 Comment(0)
P
29

char *str = "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.

Personalty answered 16/3, 2009 at 21:18 Comment(2)
char str[] versus char* str results in the string being modifiable.Personalty
Here's a couple references to this: iso-9899.info/wiki/StringsByExample securecoding.cert.org/confluence/display/cplusplus/…Personalty
R
4

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.

Recall answered 16/3, 2009 at 21:10 Comment(0)
T
3

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);
Tremor answered 17/3, 2009 at 1:59 Comment(0)
Z
2

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

Zymo answered 16/3, 2009 at 21:11 Comment(0)
E
0

In your example, Hello wordl! is constant string, any attempt to modify this constant string will result in an exception. Instead, You can do this -

string s = "Hello wordl!";
char* ptr = &s[0];

and then play around with ptr.

Electrochemistry answered 21/8, 2018 at 9:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.