Re: Access Violation error while using pointers



John Dallman wrote:
In article <606AE501-F79F-4F68-B6A1-DABD35118F20@xxxxxxxxxxxxx>,
thejasviv@xxxxxxxxxxxxxxxxxxxxxxxxx (=?Utf-8?B?dGhlamFzdml2?=) wrote:

void main()
{
char *p="Hello";
*p='M'; //This is where the error occurs
cout<<p<<endl;
}

This code compiles and executes perfectly in Boreland C++. When I run
the same code in VC++ 6.0, however, I get the below error in
debugging mode:

Unhandled exception in Test.exe: 0xC0000005: Access Violation

Can someone please provide me a solution to this?

Just to make sure we agree on what you're trying to do, you're trying
to change the "Hello" string that p is pointing to to "Mellow"?

Changing the value of literal strings is something the C and C++
compilers are not required to support.

There is something interesting here, and I can see why thejasviv figured he
(or she) could change the string literal like that.

A string literal is itself an object, and its type is "array of const char"
(this changed in the first revision of the 1998 doc)

But now look at this assignment:

char *p="Hello";

If you look at that carefully, you'll wonder: if the string literal is an
array to const elements, why can I convert it to a non-const pointer?
Shouldn't that be an error?

Yes, it should, but doing so would severly break C's compatibiliy because
there was no "const" keyword in C, so pretty much every C function, from
those in "stdio.h" onwards, would not compile anymore.

Thus, the C++ standard specifically allows you to convert from an "array of
const char" to a "char*", even though this conversion looses the
constantness, opening the door for undefined behaviour when you try to
modify that string literal.

Best


------
Fernando Cacciola
SciSoft

http://certuscode.wordpress.com
http://fcacciola.50webs.com
http://fcacciola.wordpress.com



.



Relevant Pages