I have two version of code. One works and the other doesnot.
Working code is a follows :
int main()
{
int i;
char str[] = "Hello World";
std::cout<<"The string value before memset is : "<<str<<std::endl;
memset (str,'-',6);
std::cout<<"The string value after memset is : "<<str<<std::endl;
return 0;
}
It gives expected output :
The string value before memset is : Hello World
The string value after memset is : ------World
Now, I have another version of code in which I want to use the char pointer but this code is not working. I get the following output :
int main()
{
char *str;
str = "Hello World";
std::cout<<"The string value before memset is : "<<str<<std::endl;
memset (str,'-',6);
std::cout<<"The string value after memset is : "<<str<<std::endl;
return 0;
}
The string value before memset is : Hello World
Segmentation fault (core dumped)
I just could not figure on what is happening. Could you help me on this?
What compiler are you using? That should not compile, because "Hello World" is a const char[12], which decays to const char*. In C++ it's not valid to assign a const char* to a char*, because you cannot lose const without a cast. Modifying const data is undefined behavior, so a crash is reasonable. (Usually string literals are placed in a read-only memory segment so it will likely crash if you write to them (but that's a compiler detail, not language.))
If you want to modify the data, you must copy the string literal into your own memory. Your first is a valid way to do that.