Character array crash

I am using VC++ 6.0 IDE
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;

int main()
{
	char szArr1[] = "Hello";

	szArr1[0] = 'S';

	return 0;
}

The above code compiles fine and runs fine
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;

int main()
{
        char * szArr2 = "Hello";

	szArr2[0] = 'S';

	return 0;
}

But the above code compiles fine but while running it crashes. I tried to debug and got the following exception.
Unhandled exception at 0x00401069 in StringCrash.exe: 0xC0000005: Access violation writing location 0x0042e01c.

Can anyone explain me the exception and the reason?

Thanks.
In the first one, you allocated a char array of length 6, and you assigned it the values 'H', 'e', 'l', 'l', 'o', 0. Essentially, you did a bitwise copy of the string literal, which is why when you try to write to it, the runtime doesn't mind.

In the second one, however, you're creating a pointer to the string literal itself. String literals are stored in sections of memory that are illegal to write to.
Understood. Thanks!
Topic archived. No new replies allowed.