views:

67

answers:

1

I have the following program which is giving run time error: The instruction at "x" referenced memory at "y" The memory could not be written.

int main()
{
    char *str1 = "Rain";
    char *&str2 = str1;

    cout << str1 << str2 << endl;

    *str1 = 'M';
    cout << str1 << str2 << endl;

    *str2 = 'P';//Here the error happens
    cout << str1 << str2 << endl;

    return 0;
}

What is the cause of this error.

+5  A: 

The problem is that a string literal is technically a 'char const pointer'. Reading right to left a pointer to unmodifiable characters. Because of backward comparability with 'C' this can be auto cast to 'char pointer' by the compiler. This does not mean that the underlying type has changed and thus modifying the underlying const object is undefined behavior.

char         *str1 = "Rain";  // Lie this is not a char* 
char const*   str9 = "Rain";  // This is the real type.

// String lieterals =>   "XXXXX" are char const*

If you want to modify the string what you need to do is declare an array.

char         str6[] = "Rain";
str6[0] = 'M';
*str6   = 'P';
Martin York