#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
int replace(char * str, char c1, char c2);
int main()
{
char * str = "test";
cout << replace(str, 't', 'p');
cout << str;
cin.get();
return 0;
}
int replace(char * str, char c1, char c2)
{
int num = 0;
while (*str != '\0')
{
if (*str == c1)
{
*str = c2; // <- Unhandled exception
num++;
}
str++;
}
return num;
}
Why this is illegal?
The memory you are trying to write into belongs to the "test" string, which is most likely located in a readonly segment of your executable image, which means that it's illegal to modify it.
You might consider changing your code to:
char str[] = "test";
Which should give you a modifiable buffer on the stack.
You might consider changing your code to:
char str[] = "test";
Which should give you a modifiable buffer on the stack.
Even though C++ allows you to point to a string literal with a char* for historical and compatibility reasons, you are not allowed to modify such a string: it is hard-coded in your program. String literals should be treated as const char*€. A solution would be to declare your variable to be an array rather than just a pointer. Then the compiler would actually use the literal to initialize the array, allowing you to modify that copy of the string.
"test" is a string constant, so you shouldn't modify it because it can sit in read-only memory.
[edit]...lost the race [lol][/edit]
[edit]...lost the race [lol][/edit]
It's great that this topic showed up. I've always had a question on this ...
What is the 'string literal' really? How is it related to pointers?
How does 'string' appears to a C compiler? Is it a pointer whoose address is stored as 'abcABC'? It's quite confusing for me.
Thanks
Quote:Original post by Fruny
Even though C++ allows you to point to a string literal with a char* for historical and compatibility reasons, you are not allowed to modify such a string: it is hard-coded in your program.
What is the 'string literal' really? How is it related to pointers?
char *string = "abcABC";
How does 'string' appears to a C compiler? Is it a pointer whoose address is stored as 'abcABC'? It's quite confusing for me.
Thanks
A string literal is usually implemented as an array of characters in a read only data segment of the executable image. It has an implicit conversion to a char * that points to the first member of the string literal.
With GCC and it's decendants you can compile with the -Wwrite-strings option to have it give you a warning instead of silently casting away constness.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement