-2

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?

nzy
  • 854
  • 2
  • 15
  • 28

2 Answers2

0

I assume you have

char *str = "Hello world";

in your failing code. The memset fails because str is a pointer to a constant string. You are not allowed to change constant strings.

In the one that works

char str[] = "Hello World";

copies the constant string into a local variable. You are allowed to change that.

pm100
  • 48,078
  • 23
  • 82
  • 145
0

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.

Chris Uzdavinis
  • 6,022
  • 9
  • 16