memory management – How to solve access violation writing location error?

memory management – How to solve access violation writing location error?

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.

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.

memory management – How to solve access violation writing location error?

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);

Leave a Reply

Your email address will not be published. Required fields are marked *